Reputation: 1207
As opposed to setting individual functions to each element's click event, I would like to iterate elements and assign based on id or whatever?
document.getElementById('measure').onclick = function() { clickMe(1); };
How would I approach this?
Upvotes: 0
Views: 89
Reputation: 768
In the past I've done something along these lines:
var setClickOnElements = function(selector) {
$(selector).each(function() {
$(this).click(function(event) {
// behaviour on click
});
});
};
...where selector
is a class selector, e.g. .my-class
. Within the callback passed to each
you can get at other properties of the selected elements, e.g. id etc. If you add that class to the elements you'd like to set a click
function and call setClickOnElements('.my-class');
on load, you should be good to go!
EDIT: The above uses jQuery. If you're restricted to pure Javascript, you could use one of the methods described in John Resig's post on implementations of getElementByClass
: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
Here's an example (using Dustin Diaz's method from http://www.dustindiaz.com/getelementsbyclass):
var getElementsByClass = function(searchClass,node,tag) {
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;
}
var setClickOnElements = function(className) {
var elements = getElementsByClass(className);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.onclick = function(event) {
// click behaviour here
};
}
};
Upvotes: 1