MichD

 

JavaScript: getChildNodesByTagName()

in Blog

If you’ve ever used JavaScript’s getElementsByTagName(), you may have noticed something annoying about its behaviour. (Well, it’s only annoying depending on your application.)

getElementsByTagName returns every element matching the tag name given, regardless of its position in the document tree. This is annoying if you only want to use the elements that are direct descendants of the element you’re calling it from.

So anyway, to cut this short, I wrote a quick but effective function that works just the same as getElementsByTagName, with the difference that it only returns direct descendants. Just add in this snippet of code and you can start using the function just as you would use getElementsByTagName.

Object.prototype.getChildNodesByTagName = function (tagName) {
    var byTagName = this.getElementsByTagName(tagName),
        outArr = [],
        i;

    for (i = 0; i < byTagName.length; i++) {
        if (byTagName[i].parentNode == this) {
            outArr.push(byTagName[i]);
        }
    }

    return outArr;
}

Here’s how it works: The function uses the typical getElementsByTagName, and then iterates over all the elements found. For each element it checks whether the element’s parentNode equals this, which is the node that should be the parent of any elements we want to return. When the comparison is positive, the element is added to the array, which is later returned.

I hope you can put it to good use!

Leave me a comment if this was helpful to you, or if there’s anything wrong, please.