Javascript attach an onclick event to all links

events, javascript

Solution

getElementsByTagName is supported by all modern browsers and all the way back to IE 6

var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
    elements[i].onclick = function () {
        // stuff
    }
}

Problem

I want to attach a function on every link on the site to change a parameter. How can I do this without jQuery? How do I traverse every link (it might be a DOM item) and call a function on them?

Original source