Javascript getElementsByClass

Javascript getElementsByClass

Dont you know, there is no Javascript getElementsByClass function. Although in Javascript there is function for finding “id” that is getElementById. There is also function to find tags that is getElementsByTagName. In this case, you have to declare your own Javascript getElementsByClass.

In this Javascript getElementsByClass code, you will need to modify getElementsByTagName function a little bit. The main code should be like:

function getElementsByClass(find){
	var result = new Array(); ;
	arrs = document.getElementsByTagName("*");
	j=0;
	for(i in arrs)if(arrs[i].className && arrs[i].className == find){result[j]=arrs[i];j++;}
	return result;
}

After Declaring Javascript getElementsByClass function. You can call it like the function getElementById or getElementsByTagName. However you dont have to add “document” in front of  Javascript getElementsByClass function.

You can copy bellow codes and run to test the functionality of Javascript getElementsByClass function.

<div>well done</div>
<p>klnsadkjfnakfjnk lskajfjalsndjkn</p>
<span>you have</span>
<div>23jn2jn kjk2n3n 23jn 2kjn3</div>
<p>found me</p>
<span>23jn n j2n3jn nk2n3j n2n 2jn j23kn</span>
<script>
function getElementsByClass(find){
	var result = new Array(); ;
	arrs = document.getElementsByTagName("*");
	j=0;
	for(i in arrs)if(arrs[i].className && arrs[i].className == find){result[j]=arrs[i];j++;}
	return result;
}

arrs2 = getElementsByClass("findme");
for(i in arrs2) alert(arrs2[i].innerHTML);
</script>

Good Luck, Hope this Javascript getElementsByClass will be useful for you.

http://septiadi.com/2011/03/16/javascript-getelementsbyclass/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: