Acolos
Acolos

Reputation: 75

Using jQuery to add paragraph tags and skip HTML elements

I have some HTML being fed in to me for blogs and want to be able to ensure it's parsed properly.

I am using this jQuery function (below) to ensure text is being wrapped in a paragraph tag however it seems to be filtering out the strong and a tags into their own paragraph tags.

Here is the original HTML:

<div id="demo">
  <h2>This is a title</h2>
  This is content that will need to be wrapped in a paragraph tag <strong>and this is bold</strong> and this is a <a href="">link</a>.<br />
  More content here.
</div>

Now using this function to filter this:

$('#demo')
  .contents()
  .filter(function() {
    return this.nodeType === 3 && $.trim(this.textContent).length;
  })
  .wrap('</p>');

Renders me this HTML:

<div id="demo">
  <h2>This is a title</h2>
  <p>This is content that will need to be wrapped in a paragraph tag </p>
  <strong>and this is bold</strong>
  <p> and this is a </p>
  <a href="">link</a>.
  <p>More content here.</p>
</div>

As you can see, I'm getting half of what I need but it's separating the HTML elements outside of the paragraph tag. Is there a way I can allow these HTML elements to remain inside the paragraph tag?

Thanks

Upvotes: 0

Views: 135

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

You can store the h2 element, remove it from the structure, wrap what remains and add back in the h2.

let cloned = $("#demo > h2").clone(); // Clone the <h2>
$("#demo > h2").remove();             // Remove the <h2>
$("#demo").wrapInner("<p>");          // Wrap everyting left over
cloned.insertBefore("p");             // Put <h2> back

console.log($("#demo").html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo">
  <h2>This is a title</h2>
  This is content that will need to be wrapped in a paragraph tag <strong>and this is bold</strong> and this is a <a href="">link</a>.
  More content here.
</div>

Upvotes: 1

Related Questions