I need to pass an html line with an id coming from javascript, I used innerHTML but I can't get it to work, if I use a simple string it works
function passid(id){
var lengthOfName = id
document.getElementById('output').innerTEXT = "<input type="text" id="test" name="test" value="'lengthOfName'">";
};
<div id="output"></div>
CodePudding user response:
you should use backticks and innerHTML.
function passid(id){
var lengthOfName = id
document.getElementById('output').innerHTML = `
<input type="text" id="test" name="test" value=${lengthOfName}>`;
};
CodePudding user response:
What you have to do is some small fixes
function passid(id){
var lengthOfName = id
document.getElementById('output').innerHTML = `<input type="text" id="test" name="test" value="${lengthOfName}">`;
};
CodePudding user response:
In your example code, you are using innerTEXT with a string of HTML. This will not parse the HTML in your string and input element to the DOM.
Depending on how your are 'passing your id using javascript', you may need to defer the code as suggested in one of the comments. But you can use insertAdjacentHTML with 'afterbegin' as the placement of the HTML string. Also I would use template literals and encase your variable dollar sign and curly brackets like so => ${id}
.
See my example, if this is not what you are looking for please let me know and I will properly address my answer.
let id = "myid";
function passid(id){
let el = document.getElementById('output');
let str = `<input type="text" id="test" name="test" value="${id}">`;
el.insertAdjacentHTML('afterbegin', str);
};
passid(id);
<div id="output"></div>