0

I have an h2 and some text:

<h2>Test</h2> Lorem ipsum dolor hener ait 

I need need to wrap the text "lorem ipsum dolor hener ait" in a <p> element. Hoping to get this result:

<h2>Test</h2> <p>Lorem ipsum dolor hener ait</p> 

Currently, I have this:

$('h2').each(function() { $(this).next().wrapAll('p'); }); 

But it does not work. How I can resolve this issue?

1
  • Can you show more of the HTML please? Particularly, what comes after the text that needs to be wrapped? Commented Nov 16, 2020 at 13:31

2 Answers 2

1

You can achieve this without jQuery.

Text are HTML nodes, so you can access them using nextSibling.

for (let h2 of document.querySelectorAll("h2")) { let text = h2.nextSibling; let p = document.createElement("p"); h2.parentNode.insertBefore(p, text); p.appendChild(text); } 

If it doesn't work as expected, the problem is that h2.nextSibling is not returning the text node, but another "invisible" text node you may have between the element and the current text. Just check your HTML with F12 and debug.

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

Comments

1

You can get all text nodes of the parent and wrap them with a p element. I don't know if this solution will work for your html structure though.

contents() will return all nodes including text nodes. The filter() I use makes sure only textnodes that contain characters get wrapped. White space for code alignment are textnodes as well.

$('h2').each(function() { var textnodes = $(this).parent().contents().filter(function() { return this.nodeType === Node.TEXT_NODE && this.nodeValue.trim() !== ''; }).wrapAll('<p>'); });
p { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <h2>Test</h2> Lorem ipsum dolor hener ait </div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.