Get id of div from its class name

前端 未结 2 1908
面向向阳花
面向向阳花 2021-01-04 02:42

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 ?

相关标签:
2条回答
  • 2021-01-04 02:51
    document.getElementsByClassName('myClassName')[0].id
    

    or

    document.querySelector('.myClassName').id
    
    0 讨论(0)
  • 2021-01-04 03:00

    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.

    0 讨论(0)
提交回复
热议问题