Sasha Grievus
Sasha Grievus

Reputation: 2686

Adding a DOM element by changing innerHtml of a div prevents it to be found later with getElementById?

I have a div and I'm using javascript to add a new element inside it

Original Div:

<div id="foo"></div>

JavaScript:

document.getElementById('foo').innerHTML ="<div id='bar'></div>";

Result

<div id="foo">
  <div id="bar"></div>
</div>

But after executing this code I try to retrieve the element (in order to focus on it) doing

 document.getElementById('bar')

But this returns an empty object.

So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?

Upvotes: 2

Views: 27

Answers (2)

Narkhede Tushar
Narkhede Tushar

Reputation: 683

I would suggest using createElement and appendChild

    var barDiv = document.createElement('div');
    barDiv.id = 'bar';
    document.getElementById('foo').appendChild(barDiv);
    document.getElementById('bar').innerHTML = 'bar';
    
    console.log(document.getElementById('bar'));
<div id="foo">Foo</div>

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44105

It works perfectly - make sure you're running it in the correct order:

document.getElementById('foo').innerHTML ="<div id='bar'>Bar</div>";
console.log(document.getElementById("bar"));
<div id="foo">Foo</div>

Upvotes: 2

Related Questions