Why does `childNodes` return a number larger than I expect?

前端 未结 6 2145
有刺的猬
有刺的猬 2020-12-01 17:02

Could you please look at this jsFiddle example, and tell me why the number \'11\' is alerted rather than \'5\' (the number of

  • elements)?

    From

  • 6条回答
    •  小蘑菇
      小蘑菇 (楼主)
      2020-12-01 17:42

      You have text nodes there.

      You can skip them while iterating with...

      for (var i = 0, length = list_items.length; i < length; i++) {
          if (list_items[i].nodeType != 1) {
              continue;
          }
          // Any code here that accesses list_items[i] will sure to be an element.
      }
      

      jsFiddle.

      Alternatively, you could do it in a more functional way...

      list_items = Array.prototype.filter.call(list_items, function(element) { 
                       return element.nodeType == 1;
                   });
      

      jsFiddle.

      You must use convert it to a proper array to use the filter() method. childNodes property returns a NodeList object.

    提交回复
    热议问题