2011-01-13 142 views
3

我有3個div,我想用另一個div的開始標記替換第一個div,用替換結束標記替換第三個div。這就是我的意思:replaceWith自動關閉標記

<div>1</div> 
<div>2</div> 
<div>3</div> 

當我試圖取代(使用replaceWith())與<div class="foo">第一個div和第三與</div>,jQuery的有點曲解它:

<div class="foo"></div> 
<div>2</div> 
</div> 

雖然什麼其實我要的是:

<div class="foo"> 
<div>2</div> 
</div> 

謝謝你在前進,

回答

2

您應該使用整個元素而不是HTML代碼塊。想一想另一種方法是:

// Get the div you want 
var good = $('div:eq(1)'); 
// Remove the others 
$('div').not(good).remove(); 
// Wrap the div you want 
good.wrap('<div class="foo">'); 

如果在第一個和最後之間的多個div,你可以這樣做:

$('div:first').replaceWith('<div class="foo">'); 
$('div.foo').nextAll('div').appendTo('div.foo'); 
$('div.foo :last').remove(); 

觀看演示:http://jsfiddle.net/TBMHt/

+0

但在這種情況下,我不知道這兩個div之間有多少,所以這個方法不能使用。有沒有辦法找到兩個div之間的內容? – Warrantica 2011-01-13 11:03:14