How do I loop through children objects in javascript?

前端 未结 6 1842
梦如初夏
梦如初夏 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: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.

提交回复
热议问题