JavaScript不去除div内的所有元素 [英] Javascript not removing all elements within a div

查看:126
本文介绍了JavaScript不去除div内的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建这段JavaScript代码是为了移除div内的所有输入

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.

推荐答案

那是因为你跳过了项目,同时从活动节点列表中移除。

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

删除索引为0的项目时,处于索引1的项目需要索引0,因此,如果迭代已经在索引1上,则不会删除它。

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]);
   }
}

这篇关于JavaScript不去除div内的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆