Javascript 从类名中获取 div 的 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6773550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get id of div from its class name
提问by Zac
How can I find an id based on its class just using javascript. I know this is easy with jQuerywhat is the solution.. using getElementsByTagName ?
如何仅使用 javascript 根据其类找到 id。我知道这很容易使用 jQuery解决方案是什么..使用 getElementsByTagName ?
回答by binarious
document.getElementsByClassName('myClassName')[0].id
or
或者
document.querySelector('.myClassName').id
回答by sv_in
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.
第一步是找到具有给定类名的元素。目前有一些现代浏览器支持的功能,如getElementsByClassName
和querySelector
功能。但它们不是跨浏览器的解决方案。
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
也就是说,getElementsByClassName
IE 6-8querySelector
不支持,IE6-7 & FF3 不支持
来源: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.
因此,如果您不支持这些浏览器,那么您可以使用它们,否则您需要一个包装器 js 函数,就像最初在 justswell.org 上找到的这篇博客文章中提到的那样。