Click here to Skip to main content
15,887,936 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Is there any way to get the DIV ID using its Class in javascript.


Thanks

Dileep
Posted

SQL
document.getElementsByClassName('myClassName')[0].id
or

document.querySelector('.myClassName').id
 
Share this answer
 
Comments
dilzz 22-Aug-12 4:53am    
is there any other option, I have multiple div's in same Class name,
I need to get the correct div ID when i clicked on a particular Div Thanks
Raghunatha_Reddy_S 24-Aug-12 2:55am    
<script type="text/javascript">
function clicked(item) {
alert(item.id);
}
</script>


<div önclick="clicked(this);" id="test">test</div>
Here is the code for Javascript

<div id="div1" class="divclass">sandip</div>

<script type="text/javascript">
    var obj = document.getElementsByClassName("divclass");
    alert(obj[0].id);
</script>



Code in jquery
<div id="div1" class="divclass">sandip</div>

<script type="text/javascript">
    alert($('.divclass').attr("id"));
</script>


cheers
 
Share this answer
 
Comments
dilzz 22-Aug-12 4:52am    
is there any other option, I have multiple div's in same Class name,
I need to get the correct div ID when i clicked on a particular Div


Thanks
Sandip.Nascar 22-Aug-12 5:07am    
Why don't you access the div with id? If you have returned the object, what is the requirement to get the id?

In the e.g above,
var obj = document.getElementsByClassName("divclass");
Here obj is the collection of object (all objects that is linked with class class.
So, you need to iretae the object collection and see, which div you want.
But you need something to identify the unique div.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900