JavaScript: Chaining getElementsBy Methods

,,

How often have you run into the situation where it would be great if you could chain getElement(s)By method calls? Unfortunately JavaScript does not support this out of the box since the getElement(s)By functions return various collection objects.

Thankfully there is a way you can extend JavaScript functions and objects using prototyping. The stub would look somewhat like this, and you would have to include this in whatever pages use the chained calls:

Object.prototype.getElementByID = function(s_id)
{
alert(s_name);

return null;
}

This is just one example. Using this process you can then run effective chaining that could look like this:

document.getElementsByTagName("rule").getElementsByAttribute("format", document.getElementsByAttribute("data_format");

As soon as I have the extended methods completed, I will make them available here for download. Feel free to contribute, if you have any particular ideas on this! :)

Leave a Reply