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?