I would like to insert an element into the DOM tree so that it is shown after the paragraph that contains my target element.
For example, if my target is the SPAN element here:
Lorem <span>ipsum</span> dolor sit.
After inserting a new DIV it should look like this:
Lorem <span>ipsum</span> dolor sit.
<div>newly inserted</div>
This works fine with referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
(eg. see How to insert an element after another element in JavaScript without using a library?)
However, it leads to unexpected results when there is a second inline node inside the same paragraph:
Lorem <span>ipsum</span> dolor <b>sit</b>.
In this case the DIV will be inserted in front of the B node, breaking up the paragraph:
Lorem <span>ipsum</span> dolor
<div>newly inserted</div>
<b>sit</b>.
I understand why this is happening but it's not what I want. Is there a way to always insert the DIV after the entire paragraph, not just after the current node?
I suspect one option might be to loop through the nextSiblings until I either reach null
or find one with the CSS display
property block
?
`s in the question? I'm not sure what distinguishes the end of your "paragraph" from the rest of the document below it
– CertainPerformance Feb 11 '19 at 00:43