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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:07:47  来源:igfitidea点击:

Get id of div from its class name

javascript

提问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 getElementsByClassNameand querySelectorfunctions. but they are not cross browser solutions.

第一步是找到具有给定类名的元素。目前有一些现代浏览器支持的功能,如getElementsByClassNamequerySelector功能。但它们不是跨浏览器的解决方案。

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

也就是说,getElementsByClassNameIE 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 上找到的这篇博客文章中提到的那样