Reputation: 11
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?
Upvotes: 0
Views: 461
Reputation: 13222
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>
Upvotes: 1
Reputation: 11809
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.
Upvotes: 1