0

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

Ankush Vats
  • 3
  • 1
  • 3
  • please share the html code.Also using `for .. in` is a bad idea for iterating an array https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea – brk Aug 30 '17 at 05:24
  • Possible duplicate of [Uncaught TypeError: Cannot call method 'hasChildNodes' of undefined](https://stackoverflow.com/questions/14681051/uncaught-typeerror-cannot-call-method-haschildnodes-of-undefined) – tousif Aug 30 '17 at 05:26

3 Answers3

1

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?

sumit chauhan
  • 1,270
  • 1
  • 13
  • 18
1

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>
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

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()) 
        ....
kangsu
  • 226
  • 1
  • 6