getElementsByClassName – Finding DOM elements having class
Mostly Javascript libraries provide this function one way or another but if you are not using any of them you can use following code for finding elements on which same class is applied and can do operations on them:
function getElementsByClassName(className, tag, elm){ var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)"); var tag = tag || "*"; var elm = elm || document; var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag); var returnElements = []; var current; var length = elements.length; for(var i=0; i<length; i++){ current = elements[i]; if(testClass.test(current.className)){ returnElements.push(current); } } return returnElements; }
This can be useful for elements which are generally shown on both top and bottom of the pages like success and error messages. where using id is difficult way to navigate to these elements.
Most Commented Posts
ajax, javascript, problem, web, website
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments
No comments yet.
Leave a comment