简体   繁体   中英

Wrap a new div element around specific text

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.

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>');
});

FIDDLE

Since jQuery does'nt really get textnodes, the native nextSibling should work.

为此,您可以在$('。ContentDiv')之后添加div,然后将html添加到其中。

$("<div id='new_div'></div").insertAfter($('.ContentDiv')).html("Share your knowledge. <a href='URL'>Be the first to write a review »</a>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM