nick
nick

Reputation: 3259

Alternative to document.body.innerHTML += htmlstring

I have a function that does this:

document.body.innerHTML += '<div>lorem ipsum</div>';

and it works fine but it breaks my references of other divs (I've read that this is because it parses the body again). Is there a vanilla alternative using only Javascript?

Upvotes: 2

Views: 3561

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

Two ways I can see

document.body.appendChild(document.createElement('div')).app‌​endChild(document.cr‌​eateTextNode('lorem ipsum'))

which is just shorthand for

var div = document.createElement('div');
var text = document.createTextNode('lorem ipsum');
div.appendChild(text);
document.body.appendChild('div');

or

document.body.insertAdjacentHTML('beforeEnd', '<div>lorem ipsum</div>');

documentation:

Upvotes: 2

brk
brk

Reputation: 50336

You can append it another div

document.getElementById("demoDiv").innerHTML += '<div>Test 22</div>';
<div>Test</div>
<div id="demoDiv"></div>

Upvotes: 1

Related Questions