inicio mail me! sindicaci;ón

Get elements by CSS class name in javascript

Dustin Diaz wrote a nice, efficient version of getElementByClassName(), which searches HTML elements and retrieves all the items with a given CSS class specified.

Of course, if you use a lib like extjs, jQuery, et al, then you have no need of this. But if you’re trying to hack out a greasemonkey script or insert some minimalist code, here it is.

And here it is, for my own archives:

?View Code JAVASCRIPT
function getElementsByClass(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;
}

Here’s another alternative I found on Glazblog, using xpath to search the document:

?View Code JAVASCRIPT
document.getElementByClassName = function(needle) {
  var xpathResult = document.evaluate('//*[@class = needle]', document, null, 0, null);
  var outArray = new Array();
  while ((outArray[outArray.length] = xpathResult.iterateNext())) {
  }
  return outArray;
}

I don’t really know which is more efficient, though I suspect the xpath search could be taxing in very large documents. I’m positive, based on IE’s fake implementation of key/value pairs in the DOM, that they both suck in IE, even if you specify a specific tag type to search. Obviously, providing a node makes the regular expression search faster, by virtue of having less content to parse.

Comments are closed.