Reputation: 1842
How can I keep a reference to a newly created element (createElement()
), that I inserted after an existing element in the DOM (insertAdjacentHTML()
)?
In this example, you can see that the color doesn't change, if I use elNew
/elNewInner
after insertAdjacentHTML()
:
var elOrig = document.getElementById('insertAfter');
// Create new element
var elNew = document.createElement('div'),
elNewInner = document.createElement('div');
elNewInner.textContent = 'I\'m a new element, but I\'m not red';
elNew.appendChild(elNewInner);
elOrig.insertAdjacentHTML('afterend', elNew.outerHTML);
// This doesn't change the color in the DOM
elNewInner.style.color = 'red';
<div id="insertAfter">Insert new element after me</div>
Is there any way to keep an reference to an element after I use insertAdjacentHTML
or are there other ways in JavaScript to achieve the same?
Upvotes: 3
Views: 3280
Reputation:
Better approach than using .insertAdjacentHTML
with .outerHTML
like that would be to use .insertBefore
from the .parentNode
of elOrig
.
var elOrig = document.getElementById('insertAfter');
// Create new element
var elNew = document.createElement('div'),
elNewInner = document.createElement('div');
elNewInner.textContent = 'I\'m a new element, but I\'m not red';
elNew.appendChild(elNewInner);
elOrig.parentNode.insertBefore(elNew, elOrig.nextSibling)
// This doesn't change the color in the DOM
elNewInner.style.color = 'red';
<div id="insertAfter">Insert new element after me</div>
This inserts elNew
before the .nextSibling
of elOrig
, which is effectively the same as putting it "afterend"
using insertAdjacentHTML
.
With your original way, you were taking the new elements, converting it to HTML then making new elements from that HTML, which is certainly going to be slower, and is ultimately appending a copy.
Upvotes: 3