I have a button in a webpage that is linked to a Javascript function, which creates a div as follows:
function creatediv(){
var div = document.createElement('div');
div.innerHTML = document.getElementById('innerhtmlbox').value;
document.body.appendChild(div);
}
However, it is not working. Can anyone give me any advice?
I have a button in a webpage that is linked to a Javascript function, which creates a div as follows:
function creatediv(){
var div = document.createElement('div');
div.innerHTML = document.getElementById('innerhtmlbox').value;
document.body.appendChild(div);
}
However, it is not working. Can anyone give me any advice?
Share Improve this question edited Nov 30, 2020 at 18:55 leonheess 21.6k19 gold badges94 silver badges136 bronze badges asked Oct 15, 2015 at 17:31 PythonicPythonic 1732 gold badges3 silver badges10 bronze badges 6-
what is
document.getElementById('innerhtml').value
– Sandeep Nayak Commented Oct 15, 2015 at 17:32 - First I'd just put alert("hey"); to make sure your button click is actually being registered... – Luke Twomey Commented Oct 15, 2015 at 17:33
- 1 Works perfectly fine for me -> jsfiddle/t4c5yq24 – adeneo Commented Oct 15, 2015 at 17:34
- is document.getElementById('innerhtml') a form element? if not, the result of value seems doubtful to me. – ZPiDER Commented Oct 15, 2015 at 17:35
- 2 Protip: for the sake of readability don't name your element after a DOM attribute. It can get confusing. – Sterling Archer Commented Oct 15, 2015 at 17:35
2 Answers
Reset to default 5Try this:
function createDiv() {
let div = document.createElement('div');
div.innerText = document.getElementById('getText').innerText;
document.body.appendChild(div);
}
<button onClick="createDiv()">Click me!</button>
<div id="getText" style="display: none;">
INNER TEXT
</div>
You need to use innerText
function creatediv() {
var div = document.createElement('div');
div.innerHTML = document.getElementById('innerhtml').textContent;
document.body.appendChild(div);
}
creatediv();
http://jsfiddle/e8jn9pj5/3/
Or if you are populating it from button's value you may use .value as suggested by adeneo
http://jsfiddle/t4c5yq24/