2017-08-30 54 views
0

我来自python背景,所以如果这听起来很愚蠢,那么请允许我批评。但是我有三个元素,我已经将它们存储在单独的变量中,然后从这些变量中创建一个数组。如何将dom元素传递给javascript函数?

var item = document.getElementById("s-tools"); 
var item2 = document.getElementById("s-tools2"); 
var item3 = document.getElementById("s-tools3"); 
var arr = [item, item2, item3] 

现在我想在我for循环中迭代这个dom对象的数组,并从这些项中移除子元素。

for (var item in arr) { 
    while (item.hasChildNodes()) { 
      item.removeChild(item.lastChild); 
      } 
    } 

则在项目抛出下面的错误和值为0

Uncaught TypeError: item.hasChildNodes is not a function

+0

请分享html代码。同样使用'for .. in'对于迭代数组是个不错的主意 https://stackoverflow.com/questions/500504/why-is-using-for-in- with-array-iteration-a-bad-idea – brk

+0

[Uncaught TypeError:Can not call method'hasChildNodes'of undefined]可能的重复(https://stackoverflow.com/questions/14681051/uncaught-typeerror-cannot-call-method -haschildnodes-of-undefined) – tousif

回答

0

似乎更容易做

document.querySelectorAll('#s-tools, #s-tools2, #s-tools3').forEach(el => { 
 
    while (el.firstChild) el.firstChild.remove(); 
 
});
<div id="s-tools"> 
 
    <span>child 1</span> 
 
</div> 
 
<div id="s-tools2"> 
 
    <span>child 2</span> 
 
    child 3 
 
</div> 
 
<div id="s-tools3"> 
 
    <div>child 4</div> 
 
</div>

1

由于您使用的每个循环,项目将成为你的关键。在array数组中,item是数组的索引,并且您试图执行函数removeChild on数组索引,这就是为什么得到错误。您需要提供执行功能的确切元素

请参阅代码段。

var item = document.getElementById("s-tools"); 
 
var item2 = document.getElementById("s-tools2"); 
 
var item3 = document.getElementById("s-tools3"); 
 
var arr = [item, item2, item3] 
 

 
for (var item in arr) { 
 
    while (arr[item].hasChildNodes()) { 
 
      arr[item].removeChild(arr[item].lastChild); 
 
      } 
 
    }
<div id="s-tools"> 
 
    <p>para</p> 
 
</div> 
 
<div id="s-tools2"><p>para</p> 
 
</div> 
 
<div id="s-tools3"><p>para</p></div>

见下面的链接以供参考:” https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

For-each over an array in JavaScript?

+0

工作就像一个魅力!谢谢!我会在6分钟内接受答案! –

+0

很高兴帮助你的男人。 –

+0

但有没有其他可能更优雅的方式来做到这一点? –

相关问题