2011-10-31 101 views
3

有什麼辦法去除元素,除了內部因素:jQuery的:刪除元素,除了內部元素

<div class="gallery"> 
    <a href="images/rep.png" title="rep"> 
    <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep"> 
    </a> 
</div> 

<div class="gallery"> 
    <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep"> 
</div> 

我寫了這個代碼,但不工作:

$(".gallery").contents().filter(".thumbnail").remove(); 

回答

10

jQuery有一個unwrap()方法,它刪除父節點並保留匹配的元素:

$(".gallery").contents().filter(".thumbnail").unwrap(); 

// or (faster) 
$(".gallery .thumbnail").unwrap(); 
+1

或'$( 「畫廊.thumbnail。」)解開();' – nnnnnn

+0

@nnnnnn:是啊,只是編輯在:-) –

+0

@AndyE:感謝安迪 – Nulled

0

可能是一個更簡單的方法,但是:

$('.gallery').each(function() { 

    var img = $(this).find('img'); 
    $(this).children("a").remove(); 

    $(this).append(img); 

}); 
0

嘗試

innerhtml = $("div.gallery .thumbnail").get(); 
$("div.gallery").html(innerhtml);