Let's say I have:
<body>
<div class="root">
<div class="text1"></div>
<div class="text2"></div>
</div>
</body>
And want to insert some HTML after text2
.
var targetHandle = document.querySelector('.root')
targetHandle.insertAdjacentHTML( 'beforeEnd', `
<div class="text3"></div>
`);
We can get that handle two ways:
var targetHandle = document.querySelector('.root')
var newNode1 = targetHandle.lastElementChild
var newNode2 = document.querySelector('.root > .text3')
So far so good. But if the contents of insertAdjacentHTML
is very large and contained many nodes:
var targetHandle = document.querySelector('.root')
targetHandle.insertAdjacentHTML( 'beforeEnd', `
<div class="text3"></div>
<div class="text4"></div>
<div class="text5"></div>
`);
Using document.querySelector
becomes a real burden to find every top level node, and a lastElementChild
selector would only point to the last element being injected.
You might say, that's so silly, just wrap these DOM nodes with a parent so you can query and traverse that:
var targetHandle = document.querySelector('.root')
targetHandle.insertAdjacentHTML( 'beforeEnd', `
<div class="parentToTheRescue">
<div class="text3"></div>
<div class="text4"></div>
<div class="text5"></div>
</div>
`);
And while this is a valid way to find these Nodes, we've made a compromise to our solution by creating HTML as a way to get them.
What I really want is a way to get handles of each top level Node being injected with insertAdjacentHTML
but without the compromise of needing a parent wrapper:
var nodeList = [ ... ]
Couple ideas I have, which I'm not crazy about so far because I fear performance issues:
Use the parent wrapper anyway. After inserting get handles to child nodes. Copy/paste the children to the parents level, delete the parent.
Take a snapshot of the existing Nodes in the tree I'm about to paste into. After inserting take another snapshot and diff to find the new Nodes.
Looking for other ideas! Thanks