How do I loop through children objects in javascript?

前端 未结 6 1816
梦如初夏
梦如初夏 2020-12-24 10:36

I have this code in a function:

tableFields = tableFields.children;
for (item in tableFields) {
    // Do stuff
}

According to a console.lo

相关标签:
6条回答
  • 2020-12-24 11:10

    In ECS6, one may use Array.from():

    const listItems = document.querySelector('ul').children;
    const listArray = Array.from(listItems);
    listArray.forEach((item) => {console.log(item)});
    
    0 讨论(0)
  • 2020-12-24 11:15

    if tableFields is an array , you can loop through elements as following :

    for (item in tableFields); {
         console.log(tableFields[item]);
    }
    

    by the way i saw a logical error in you'r code.just remove ; from end of for loop

    right here :

    for (item in tableFields); { .

    this will cause you'r loop to do just nothing.and the following line will be executed only once :

    // Do stuff
    
    0 讨论(0)
  • 2020-12-24 11:15

    In the year 2020 / 2021 it is even easier with Array.from to 'convert' from a array-like nodes to an actual array, and then using .map to loop through the resulting array. The code is as simple as the follows:

    Array.from(tableFields.children).map((child)=>console.log(child))
    
    0 讨论(0)
  • 2020-12-24 11:22

    I’m surprised no-one answered with this code:

    for(var child=elt.firstChild;
        child;
        child=child.nextSibling){
      do_thing(child);
    }
    

    Or, if you only want children which are elements, this code:

    for(var child=elt.firstElementChild;
        child;
        child=child.nextElementSibling){
      do_thing(child);
    }
    
    0 讨论(0)
  • 2020-12-24 11:27

    The backwards compatible version (IE9+) is

    var parent = document.querySelector(selector);
    Array.prototype.forEach.call(parent.children, function(child, index){
      // Do stuff
    });
    

    The es6 way is

    const parent = document.querySelector(selector);
    Array.from(parent.children).forEach((child, index) => {
      // Do stuff
    });
    
    0 讨论(0)
  • 2020-12-24 11:30

    The trick is that the DOM Element.children attribute is not an array but an array-like collection which has length and can be indexed like an array, but it is not an array:

    var children = tableFields.children;
    for (var i = 0; i < children.length; i++) {
      var tableChild = children[i];
      // Do stuff
    }
    

    Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.

    0 讨论(0)
提交回复
热议问题