Blog > detail

Just my tiny mind

Javascript getElementsByClass

26-2-2012 Admin General 2 Comments

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.


 


Javascript getElementsByClass Javascript getElementsByClass Javascript getElementsByClass

Javascript getElementsByClass

word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word

Javascript getElementsByClass

Javascript getElementsByClass

Javascript getElementsByClass