Using Javascript DOM to Get Elements But Exclude Children
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