2016-09-18 13 views
1
私は <a>タグを除く要素のすべての子を削除したい

以外のすべての子要素を削除し、私は <a>タグ

$("#tagId").children().remove(); 

を使用しますが、それは私はそれをどのように行うことができ、子供たちのすべてを削除しますか?

答えて

5

使用notアンカータグに

$("#tagId").children().not('a').remove();

+1

非常に簡単で良い答え – pejman

+0

お手伝いします。これで問題が解決した場合は、回答としてマークしてください。 –

2

aを除外するために、セレクタを使用します。

$("#b").click(function() { 
 
    $("#tagID").children(":not(a)").remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="tagID"> 
 
    <span>This SPAN should be removed</span><br> 
 
    <a href="#">This A should be kept</a><br> 
 
    <div>This DIV should be removed</div> 
 
</div> 
 
<button id="b">Click me</button>

0

を除外するためのjQueryを必要としない解決策があります:

var container = document.getElementById('container') 

Array.from(container.children).filter(function(child) { 
    return !(child instanceof HTMLAnchorElement) 
}).forEach(function(child) { 
    container.removeChild(child) 
})