Reputation: 1609
I have a container span element,in this span, I have couple child span elements like:
<span>
<span>o</span>
<span>r</span>
<span>l</span>
<span>d</span>
</span>
The previous span before the above container span is called preElement, the structure is:
<span>w</span>
What I want to do is insert all child elements in the container after preElement. The new structure should be:
<span>w</span>
<span>o</span>
<span>r</span>
<span>l</span>
<span>d</span>
What I did is :
for (var i = 0; i < container.children.length; i++) {
preElement.parentNode.insertBefore(container.children[i],
preElement.nextSibling);
preElement = preElement.nextSibling;
}
Can you guys let me know why it's not correct?
Upvotes: 1
Views: 55
Reputation: 56895
The issue is that looping through the children by index will be incorrect because child[i]
will be removed from the list in the call to insertBefore
resulting in skipped elements.
You can treat the children of container
like a stack and keep popping the last child of the container and inserting it after preElement
until empty:
const [preElement, container] = document.getElementsByTagName("span");
while (container.children.length) {
preElement.parentNode.insertBefore(
container.children[container.children.length-1],
preElement.nextSibling
);
}
<span>w</span>
<span>
<span>o</span>
<span>r</span>
<span>l</span>
<span>d</span>
</span>
Or, sticking to your approach of moving preElement
to the next sibling repeatedly:
let [preElement, container] = document.getElementsByTagName("span");
while (container.children.length) {
preElement.parentNode.insertBefore(
container.children[0],
preElement.nextSibling
);
preElement = preElement.nextSibling;
}
<span>w</span>
<span>
<span>o</span>
<span>r</span>
<span>l</span>
<span>d</span>
</span>
Upvotes: 1