How to getElementsByClassName in JavaScript and manipulating those


26 of November2007

What if you wanted all of your elements on the page that have the same class=”" to behave the exact same way. Well, with a little JavaScript, this is possible, thanks to Netlobo.com:

Note: You must add the following onload event to your body tag: < body onload=”loadClassNames()”>

<script language="javascript" type="text/javascript">

//function that allows us to get the elements by a class name,

document.getElementsByClassName = function(clsName){

	var retVal = new Array();
	var elements = document.getElementsByTagName("*");

	for(var i = 0;i < elements.length;i++){
		if(elements[i].className.indexOf(" ") >= 0){
			var classes = elements[i].className.split(" ");

			for(var j = 0;j < classes.length;j++){
				if(classes[j] == clsName){
					retVal.push(elements[i]);
				}
			}

		}else if(elements[i].className == clsName){
			retVal.push(elements[i]);
		}
	}
	return retVal;
}

function loadClassNames(){
	//this method only works for event handlers

	var classNames= document.getElementsByClassName('test2');

	for (var i = 0; i < classNames.length; i++){
		classNames[i].onmouseover = function(){
			alert(this.id);
		}

	}
}

</script>

The first function simply adds the capability of getting an element by class name, which is not inherently possible with JavaScript. Now, what the 2nd function does, is the following. If you add loadClassNames() as an “onload” function to the body tag, when the page loads, the function will get all of the elements with a class name of ‘test2′, and assign a new “mouseover” event. In this case, it will create a popup that displays the id of the element.

Add Your Own


bluehost.com ad


Recent Posts

  • Lessons learned from Apple&#39;s Design Process
  • On why I started another Redesign when I had just finished one.
  • Why I chose Bluehost for cheap, reliable hosting (review)
  • Break; and continue; in javascript loops
  • Writing a prototype function in JavaScript
  • -->