74

これは簡単な答えがあるように思えますが、私はそれを見つけることができません。たぶん私は間違った用語を検索していますか?ライブラリは使用しないでください。クロスブラウザフォールバックは必要ありませんが、このプロジェクトのすべての最新バージョンを対象としています。

私はいくつかの要素を取得しています:

element = document.querySelectorAll(".someselector");

これは機能していますが、これらの要素を削除するにはどうすればよいですか?それらをループして実行するelement.parentNode.removeChild(element);必要がありますか、それとも私が欠けている単純な関数がありますか?

4

3 に答える 3

85

はい、あなたはほとんど正しいです。凍結されたNodeList.querySelectorAllを返します。あなたはそれを繰り返して物事を行う必要があります。

Array.prototype.forEach.call( element, function( node ) {
    node.parentNode.removeChild( node );
});

結果が1つしかない場合でも、次のようにインデックスを介してアクセスする必要があります。

elements[0].parentNode.removeChild(elements[0]);

1つの要素のみをクエリする場合は、代わりにを使用します.querySelector。そこで、インデックスを使用してアクセスする必要なしに、ノード参照を取得するだけです。

于 2012-10-29T16:35:43.167 に答える
62

NodeListすでにサポートされているので、forEach次を使用できます。

document.querySelectorAll(".someselector").forEach(e => e.remove());
<div>
  <span class="someselector">element 1</span>
  <span class="someselector">element 2</span>
  there shouldn't be any of the above "element" spans after you run the code
</div>

NodeList.prototype.forEach()およびElement.remove( )を参照してください

InternetExplorerのサポート。IEは上のをサポートしていません。IEはforEachオブジェクトのメソッドNodeListもサポートしていません。したがって、上記のコードもIEで実行する場合は、JavaScriptコードの先頭に次の行を追加し、要素を削除するには、代わりにNode.removeChildを使用します(またはElement.remove()ポリフィルを使用します) )::removeElement

if (!NodeList.prototype.forEach && Array.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}
// ..then continue as usual with the forEach
document.querySelectorAll(".someselector").forEach(e => e.parentNode.removeChild(e));
<div>
  <span class="someselector">element 1</span>
  <span class="someselector">element 2</span>
  Should be empty
</div>

于 2017-09-26T11:11:14.127 に答える
26

Array.fromChildNode.removeでさらに簡潔に:

Array.from(document.querySelectorAll('.someselector')).forEach(el => el.remove());

さて、NodeListが反復可能であるのを見ただけなので、さらに短くすることができます。

document.querySelectorAll('.someselector').forEach(el => el.remove());
于 2019-01-24T09:20:49.643 に答える