This is one of the useful function in my code bank. This function can be used to find the elements by css class name. If you don't use jQuery, it will be definitely helpful for you.
Code Snippet
function getElementsByClassName(node,classname)
{
if (node.getElementsByClassName)
{
// use native implementation if available
return node.getElementsByClassName(classname);
}
else
{
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Sample Usage
function toggle_visibility(className)
{
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++)
{
var e = elements[i];
if(e.style.display == 'block')
{
e.style.display = 'none';
} else
{
e.style.display = 'block';
}
}
}
Note
See original author's example here . Following is jQuery style usage.
Reference/Credit
Stack Overflow posted by CMS
Original Coder : Dustin Diaz
Author : Si Thu
I am just a normal programmer. Cool, quiet and simple person. Love to write code without pressure. Most of the time, I am reading, writing, watching movie or surfing the web.
COMMENTS
blog comments powered by