2016-09-17 29 views
1

ここで私はselect要素といくつかのオプション要素を持っています。foreachループを実行してすべてのオプション要素を削除したいのですが、最初の2つの要素だけが削除されています。コード?選択タグからすべてのオプションを削除します

<!DOCTYPE html> 
<html> 
<body> 
<p id='item'></p> 
<form> 
remove all from fruit list: 
<br> 
<select id="mySelect" size="4" class='myclass' onChange='myFunction(this.className);'> 
    <option id='for_apple'>Apple</option> 
    <option>Pear</option> 
    <option>Banana</option> 
    <option>Orange</option> 
</select> 



<script> 
let select_item = document.getElementById('mySelect'); 
let options=select_item.getElementsByTagName('option'); 
console.log('length is : '+options.length); 
Array.prototype.forEach.call(options,(elem,index,arr) => { 

    console.log(options.length); 
    select_item.removeChild(elem); 
}); 
</script> 

</body> 
</html> 
+1

私の推測では、 'options'更新が住んでいることである:2つの要素を除去した後、その長さは4-2 == 2となるので、ループはそこで停止します。 – melpomene

+0

'' select_item.innerHTML = ""; ''を使用するか、またはこれを使用します:while(options.length)select_item.removeChild(options [0]); ' –

答えて

3

ノードリストは「ライブ」なので、繰り返しを繰り返すと長さが変わり、ループが停止します。

ソリューションは後方

let select_item = document.getElementById('mySelect'); 
let options = select_item.getElementsByTagName('option'); 

for (var i=options.length; i--;) { 
    select_item.removeChild(options[i]); 
} 
+0

ライブの場合はlengthプロパティも更新する必要がありますそれをチェックする条件がなければ、無限ループが作成されますか? –

+2

'forEach'ループを開始すると、長さがチェックされ、4つの要素を反復すると仮定します。 'options [0]'で最初の要素を削除し、ノードリストを更新します。これには3つの要素があり、最初の要素は '[0]'にあります。 '[1]'の2番目の要素を取得してnodeListを再度更新すると、2つの要素、 '[0]'と '[1]'の要素があります。 forEachループは '[2]'にある3番目の要素を取得しようとしますが、nodeListが更新されるとその位置に要素がありません。 – adeneo

+0

thanks..i forループに関する別の質問があります。制約がありません。停止するタイミングを知っていますか? –

1

あなたが代わりに

let options = document.querySelectorAll('#mySelect option'); 
+0

それはノードリストを返します。そして、すべてのノードリストがライブであると言われました... –

+1

@ AL-zami [querySelectorAll](https://developer.mozilla。 org/en-US/docs/Web/API/Document/querySelectorAll)は、ライブでないノードリストを返します。 – Anirudha

+0

okありがとうございました:)...私はhttps://developer.mozilla.org/en-US/docs/をチェックしました。 Web/API/Document/querySelectorAll –

0

別のオプションは、それにforEachを呼び出す前convert the NodeList into an arrayになり非ライブquerySelectorAllを使用することができます反復することです:

[].slice.call(options).forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 

をあなたがすでにES2015 synを使用しているので税ちょうどそれを行うにはspread syntaxを使用します。

[...options].forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 

それともArray.from

Array.from(options).forEach((elem,index,arr) => { 
    console.log(options.length); 
    select_item.removeChild(elem); 
}); 
関連する問題