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 ?
document.getElementsByClassName('myClassName')[0].id
or
document.querySelector('.myClassName').id
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With