2013-02-15 43 views
2

我正在爲此付出努力。在特定文字周圍包裹一個新的div元素

如何在沒有任何類或ID的文本週圍包裝新元素?

下面是場景:

我需要新的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>'); 
    }) 
}) 

但它不是因爲它只是圍繞着<a>元素而工作d將文本留在它下面。我還需要其中的文字。

請幫忙!

預先感謝您。

〜埃琳娜

+0

您能告訴我們完整的HTML代碼嗎?什麼是'「分享你的......」的母公司' – 2013-02-15 18:01:38

+3

但是在你的標記中'div.ContentDiv'不是'分享你的知識的父母。 Be the first to write a review »'。 – undefined 2013-02-15 18:02:04

回答

4

您需要.ContentDiv後獲得下一個textnode和換行:

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

FIDDLE

因爲jQuery的一點兒也不真正得到textnodes,本地nextSibling應該工作。

+0

你在該div的末尾有'>>'而不是'>'。 – 2013-02-15 18:04:57

+0

@JamesMontagne - 哎呀,錯字!修復。 – adeneo 2013-02-15 18:05:41

+1

這似乎不包括'Be the first to write a review »'。 – j08691 2013-02-15 18:07:23

0

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