Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of div from its class name

Tags:

javascript

How can I find an id based on its class just using javascript. I know this is easy with jQuery what is the solution.. using getElementsByTagName ?

like image 498
Zac Avatar asked Jul 21 '11 08:07

Zac


2 Answers

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

or

document.querySelector('.myClassName').id
like image 85
binarious Avatar answered Oct 02 '22 09:10

binarious


First step would be find the element(s) with the given class name. There are currently some functions supported by modern browsers like getElementsByClassName and querySelector functions. but they are not cross browser solutions.

That is, getElementsByClassName is not supported by IE 6-8 and querySelector is not supported by IE6-7 & FF3
source: http://www.quirksmode.org/dom/w3c_core.html

Therefore if you are not supporting these browsers then you can use them else you would need a wrapper js function like one mentioned in this blog post originally found on justswell.org.

like image 1
sv_in Avatar answered Oct 02 '22 07:10

sv_in