Search code examples
javascriptjquerydomdom-manipulationinsertadjacenthtml

Using insertAdjacentHTML() to add partial HTML


I have a very long text wrapped in a single <p> tag. like this:

<p>
Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod...
</p>

I need to break up that text into smaller paragraph chunks by using javascript or jquery to insert </p><p> into certain parts of the text, Effectively ending the last paragraph and then starting a new one (I already have some javascript which identifies where I want to insert the new HTML - that works fine). I've been using insertAdjacentHTML() to add the new paragraph tags:

TheElmToInsertNextTo.insertAdjacentHTML('beforebegin','</p><p>');

The trouble is: the browser tries to fix my partial html and keeps wrapping it in additional <p> tags like this:

<p>
Lorem ipsum dolor
<p></p><p></p>
sit amet consectetur adipiscing elit sed do eiusmod...
</p>

As a result: the extra <p> tags break my pagination script (from easyPaginate) which otherwise works great.

Is there a better way to insert partial HTML without the browser "fixing" it by adding additional <p> tags? (the issue occurs in both firefox and chrome)


Solution

  • Thanks to @Barmar for pointing out that this can't be done in the order that I initially thought. I fixed this by pre-processing the data on the server side before loading it into the DOM.