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';
3
  • 4
    Are you appending div to document? Use document.body.appendChild(div); Commented Nov 28, 2016 at 12:28
  • You have to insert the new div into the DOM. createElement does not do that automatically. Commented Nov 28, 2016 at 12:30
  • why does document.getElementsByTagName("header").appendChild(div) not work? Commented Nov 28, 2016 at 13:33

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

why would document.getElementsByTagName("header").appendChild(div); not work?
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.
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>

2 Comments

This is driving me crazy as document.getElementsByTagName("header").appendChild(div); is not working
try document.getElementsByTagName('header')[0].appendChild(div) as this function returns an array (-like) object.
0

You need to append the div to the document.

document.body.appendChild(div);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.