avatar

Michaël Duerinckx

 

JavaScript: getChildNodesByTagName()

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);
    var outArr = [];
    for(a=0;a<byTagName.length;a++) {
        if(byTagName[a].parentNode == this) {
            outArr[outArr.length] = byTagName[a];
        }
    }
    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.

4 comments

  1. kRiz says:

    nice :)

    and slightly homosexual :)

  2. loans says:

    Man look at our little coder boy, all grown up and publishing functions

  3. zukuvybz says:

    lol nice so pr0 ;)

  4. Mich says:

    Thanks guys ;)