Reputation: 3259
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
Reputation: 1
Two ways I can see
document.body.appendChild(document.createElement('div')).appendChild(document.createTextNode('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
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