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

前端 未结 6 2144
有刺的猬
有刺的猬 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:40

      I cobbled together a solution for this that I like. (I got the idea from this blog post.)

      1) First I get the number of child elements nodes by using:

      nodeObject.childElementCount;
      

      2) Then I wrote a function that will return any child element node by index number. I did this by using firstElementChild and nextElementSibling in a for loop.

      function getElement(x, parentNode){
          var item = parentNode.firstElementChild
          for (i=0;i

      This returns the child element I need for anything I want to pull from it. It skips the problem with childNodes retuning all the different nodes that are not helpful when trying to parse just the elements. I am sure someone more experienced than me could clean this up. But I found this so helpful that I had to post it.

    提交回复
    热议问题