How to find the div in javascript

In this javascript tutorial we will learn how to find the div that we want to find. Once during coding it became a necessary requirement for me to find a specific div, I use below mentioned code to find that div, actually I want to execute another javascript function if specific div found else nothing should be executed.

So let's have a look on how to find the div in javascript.

<script language="javascript" type="text/javascript">
function findingDiv()
{
Div_Collection = document.getElementsByTagName("div");
for (i=0;i<Div_Collection.length;i++)

{
if(Div_Collection[i].getAttribute("id") == "my_div")
{

Myfunc();

}
else
{
}
}
}
</script>

Now it’s up to you and up to condition where u will call this function. In this function first of all I get all div elements and store these div elements in a Div_Collection variable that is actually playing role as an array. It’s necessary that there must be some unique thing in the div that you are going to be find, I assigned a unique ID to the div that I am going to find. In my case that div ID is my_div. After that I apply for loop on the array and then search for that specific div by ID. If that div found then I am executing another function else nothing.

So this is the way to find the div in javascript. I hope you like this javascript tutorial.


Note:- You can also find elements other than div using this javascript technique

1 comments:

  • Swashata
     

    There is no need to use getElementsbyTagName... Instead use getElementbyId