0

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';
lovetolearn
  • 93
  • 1
  • 4
  • 11

3 Answers3

1

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>
Deep
  • 9,594
  • 2
  • 21
  • 33
  • why would document.getElementsByTagName("header").appendChild(div); not work? – lovetolearn Nov 28 '16 at 13:37
  • It does work, just keep in mind that document.getElementsByTagName("header") will give you a collection of all elements in the document with the specified tag name. So you will have to select one using []. I have updated my answer to display the same. – Deep Nov 28 '16 at 13:52
0

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>
FalcoB
  • 1,333
  • 10
  • 25
  • This is driving me crazy as document.getElementsByTagName("header").appendChild(div); is not working – lovetolearn Nov 28 '16 at 13:21
  • try document.getElementsByTagName('header')[0].appendChild(div) as this function returns an array (-like) object. – jJ' Nov 28 '16 at 18:57
0

You need to append the div to the document.

document.body.appendChild(div);