Registering a bunch of nodes for events

If for some reason you have a bunch of nodes and you really don't want to do inline events for all of them, and maybe some of these nodes are even dynamically created and the event has to be added later...Well, I suppose there are various reason someone might need to do this.

If you structure your document in such a way so that all the nodes you are interested in can be neatly obtained by one of the basic DOM methods, then you can grab a node list using one of these methods, like getElementsByTagName for example, and iterate over the list setting all the appropriate nodes to the appropriate event.

In this case, I bury the anchor nodes (<a>) I need in an unordered list. I obtain the unordered list node using getElementById. Then node.getElementsByTagName('a') will return a node list of all the anchor elements that are children of the unordered list node.

Then I just loop through and set the onclick event to all of these nodes to run a function (toggleView). The toggleView() function itself iterates over another node list of span elements, turning one off and the rest on.

And it is rather insignificant to the main idea here, but I use the innerText/textContent of the anchor nodes to determine which span element to turn off and on.

The following are just a few span elements and anchor tags, but imagine you had dozens. Having to hard code every single event registration or inserting the inline event handler in every element could get messy.

Span 1 Span 2 Span 3 Span 4 Span 5

Scripts