Javascript not removing all elements within a div

狂风中的少年 提交于 2019-12-23 13:03:18

问题


This piece of javascript code is created to remove all inputs that are within a div

function remove_inputs(){
   var elements=document.getElementById('thediv').getElementsByTagName('input');
   for(var i=0;i<elements.length;i++){
       elements[i].parentNode.removeChild(elements[i]);
   }
}

I does remove only half of elements a call and I have to call it several times in order to remove all inputs.

Please check this Jsfiddle to see it in action.


回答1:


That's because you skip items while removing from the live nodelist.

When you remove the item at index 0, the item which was at index 1 takes index 0, so you don't remove it as your iteration is already on index 1.

Do it like this :

function remove_inputs(){
   var elements=document.getElementById('thediv').getElementsByTagName('input');
   while(elements.length){
       elements[0].parentNode.removeChild(elements[0]);
   }
}



回答2:


Why don't you use jQuery instead?

function remove_inputs(){
   var elements = $('#thediv input');
   elements.remove();
}

Here is more information: http://api.jquery.com/remove/




回答3:


function remove_inputs(){
   var elements = document.getElementById('thediv').getElementsByTagName('input');
   var size = elements.length;

   for(var i = 0; i < size; i++){
       elements[i].parentNode.removeChild(elements[i]);
   }
}


来源:https://stackoverflow.com/questions/18410450/javascript-not-removing-all-elements-within-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!