繁体   English   中英

用新的div元素环绕特定文本

[英]Wrap a new div element around specific text

我正在为此奋斗。

如何在没有任何类或ID的文本周围包裹新的<div>元素?

下面是方案:

<div class="ContentDiv">.....</div>

Share your knowledge. <a href="URL">Be the first to write a review »</a>

我需要新的div来包裹“ Share your knowledge. <a href="URL">Be the first to write a review »</a>

我尝试了以下方法:

 $(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> 

但它不起作用,因为它仅环绕<a>元素,并将文本保留在其下方。 我也需要那里的其余文本。

您需要获取.ContentDiv之后的下一个textnode并将其包装:

$('.ContentDiv').each(function() {
   $(this).next('a').add(this.nextSibling).wrapAll('<div class="NewDiv"></div>');
});

小提琴

由于jQuery并没有真正获得文本节点,因此本机的nextSibling应该可以工作。

为此,您可以在$('。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>");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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