Zac
Zac

Reputation: 12836

Get id of div from its class name

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 ?

Upvotes: 20

Views: 88821

Answers (2)

sv_in
sv_in

Reputation: 14039

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.

Upvotes: 1

binarious
binarious

Reputation: 4588

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

or

document.querySelector('.myClassName').id

Upvotes: 45

Related Questions