Reputation: 83
I am struggling with this one.
How can I wrap a new <div>
element around text that does not have any class or ID?
Below is the scenario:
<div class="ContentDiv">.....</div>
Share your knowledge. <a href="URL">Be the first to write a review »</a>
I need the new div
to wrap around "Share your knowledge. <a href="URL">Be the first to write a review »</a>
"
I have tried the following:
$(document).ready(function() {
$('.ContentDiv').each(function() {
$(this).add($(this).next()).wrapAll('<div class="NewDiv"></div>');
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ContentDiv">.....</div>
Share your knowledge. <a href="URL">Be the first to write a review »</a>
but it is not working because it wraps around the <a>
element only and leaves the text below it. I need the rest of the text in there as well.
Upvotes: 2
Views: 1261
Reputation: 318182
You need to get the next textnode after .ContentDiv
and wrap that:
$('.ContentDiv').each(function() {
$(this).next('a').add(this.nextSibling).wrapAll('<div class="NewDiv"></div>');
});
Since jQuery does'nt really get textnodes, the native nextSibling
should work.
Upvotes: 4
Reputation: 8297
For this you can add a div after $('.ContentDiv') and then add the html to it.
$("<div id='new_div'></div").insertAfter($('.ContentDiv')).html("Share your knowledge. <a href='URL'>Be the first to write a review »</a>");
Upvotes: 0