0

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

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm this is close but I actually forgot to add the <br /> tag in to separate the two text lines, and to have the intetion of having two paragraph tags rather than one big one. Thanks for your answer though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.