簡體   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