Assigning behaviour to page elements based on their class name

There's little things that bore me more than having to write inline javascript for little tasks like closing a window. So I thought of a way of having javascript do it for me!

Basicly this is the idea: I assign a certain class (CloseWindow) to the items that I want to act as Window Closers, and when the page is loaded, a little script finds out the document tags with that class and assigns them a function for their onclick event.

As I wasn't feeling like writing a function for traversing the whole DOM tree for searching elements class names, I also used a function, getElementsByClass by Dustin Diaz, to discover the elements with a certain class name. So yes, the rest was pretty easy :P

Now to some code:

function getElementsByClass(searchClass,node,tag) { // Taken from var classElements = new Array(); if ( node == null ) node = document; if ( tag == null ) tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; }
The code for intercepting the onload event of the window:

window.onload = function() { // Replace all elements with 'CloseWindow' class onclick handler with a call to the windowclose function var closeWindowElements = getElementsByClass("CloseWindow"); var i; for(i=0; i < closeWindowElements.length; i++ ) { closeWindowElements[i].onclick = function() { window.close(); } } }
Finally, the code for a Window Closer element:

< button type="button" class="CloseWindow">Close< / button>
Of course all of this can be improved, you can use a custom events handler instead of just overwriting the current events of those elements, or even the current onload event of the window object, but for the purposes of demonstrating this possibility this serves completely well.

And also this is not the perfect way of having close buttons (as in the case of a site which needed to be open to the public and being completely accessible, no close buttons should be assumed as we can't assume that the users' devices are windows capable), but for sure it's going to be better than having embedded javascript in the middle of your code.

Oh, and the getElementsByClass function could be improved for allowing to discover elements with more than one class (see below), like for example class="post veryimportant". Currently the script just can detect literal values, and if you search for elements with class="veryimportant" or class="post" it will find nothing.

*Because you know that you can assign more than one class to an element, don't you? Well, now you know!