Home > javascript > Using Javascript DOM to Get Elements But Exclude Children

Using Javascript DOM to Get Elements But Exclude Children

October 30th, 2009 Adam Leave a comment Go to comments

This is a pretty basic concept, but it wasn’t immediately obvious to me at first.

I had nested DIV layers, and wanted to only get the outer level of DIVs.

For example:

<DIV id="content">
  <DIV id="parentDIV-1">
    <DIV class="childDiv"></DIV>
    <DIV class="childDiv"></DIV>
    <DIV class="childDiv"></DIV>
  </DIV>
  <DIV id="parentDIV-2">
    <DIV class="childDiv"></DIV>
    <DIV class="childDiv"></DIV>
    <DIV class="childDiv"></DIV>
  </DIV>
</DIV>

I wanted to get all of the parent DIVs from content. Of course, I kept trying to use getElementsByTagName but that would return ALL the DIVs, including the children.

I figured using childNodes would return the same results, but to my surprise, it worked! It returned only the parent DIVs! Again, this is probably very obvious to alot of people, but it wasn’t to me. Hopefully someone else who is having the same problem will stumble upon this solution.

 

In summary:
  document.getElementById("content").getElementsByTagName("div")
    returns 8 DIVs – both parents and all their children

  document.getElementById("content").childNodes
    returns 2 DIVs – only the parents

  1. quent
    December 26th, 2009 at 17:43 | #1

    Same thing here. I need to exclude the extra nodes in the childnodes. It’s probably a simple thing to do. I’m just befuddled.

  2. December 29th, 2009 at 09:56 | #2

    I’m not sure what you’re saying. Does this solution not work for you?

  1. No trackbacks yet.
*