简体   繁体   中英

how to pass dom element to javascript function?

I come from python background so spare me the criticism if this sounds silly. But I have three elements from the dom that I have stored in their separate variable and then made an array out of those variables.

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

Now I am trying to iterate over this array of dom objects in my for loop and remove child elements from these items.

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

then it is throwing the following error and value in item is 0

Uncaught TypeError: item.hasChildNodes is not a function

Since you are using for each loop, item will be you key . In array case item is array index of your array, and you trying to execution function removeChild on array index that's why you getting the error . You need to provide exact element for the function to execute

see the snippet.

 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> 

see below link for reference:" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

For-each over an array in JavaScript?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for...in loop doesn't iterates values. it iterates property names. try this.

for (var name in arr) {
    var item = arr[name];
    while (item.hasChildNodes()) 
        ....

Seems easier to do

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM