5

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.

AMD
  • 1,278
  • 4
  • 15
  • 33

3 Answers3

7

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]);
   }
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
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/

dnet
  • 1,411
  • 9
  • 19
Halo.GC
  • 41
  • 4
  • 3
    Please, don't recommend the use of a huge library just for this simple task. – Denys Séguret Aug 23 '13 at 19:31
  • JQuery is so universal it is almost always appropriate to provide a solution using it if just for any search engine results that lead to the question. – Deadron Aug 23 '13 at 19:35
-1
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]);
   }
}