Pythonic
Pythonic

Reputation: 173

Creating div on button click with Javascript not working?

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?

Upvotes: 1

Views: 12695

Answers (2)

luispcosta
luispcosta

Reputation: 572

Try 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>

Upvotes: 5

Abhas Tandon
Abhas Tandon

Reputation: 1889

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.net/e8jn9pj5/3/

Or if you are populating it from button's value you may use .value as suggested by adeneo http://jsfiddle.net/t4c5yq24/

Upvotes: 0

Related Questions