lovetolearn
lovetolearn

Reputation: 93

Why does this document.createElement("div) code not create an element?

I am really confused as to why this code does not work. I got the code from a SO page about traversing the DOM.

    var div = document.createElement('div');
    div.innerHTML = 'Y HALO THAR';

Upvotes: 0

Views: 1514

Answers (3)

Deep
Deep

Reputation: 9794

You need to append this created element into some existing element in the document

You can append it in the body as well like below in the commented code or any other element by selecting that element first and then append this JS created div inside that.

var div = document.createElement("Div");     
div.innerHTML = 'Y HALO THAR';
 //document.body.appendChild(div);

document.getElementsByTagName("header")[0].appendChild(div)
<header>
   
 </header>

Upvotes: 1

Stan George
Stan George

Reputation: 92

You need to append the div to the document.

document.body.appendChild(div);

Upvotes: 0

FalcoB
FalcoB

Reputation: 1333

you need to append the div to a element.. in my example i am adding it to a wrapper div container #wrap just creating it is not enough!

var div = document.createElement('div');
    div.innerHTML = 'Y HALO THAR';
document.getElementById('wrap').appendChild(div)
<div id="wrap">
  
  </div>

Upvotes: 0

Related Questions