javascript 选择具有两个类的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13672800/
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
Select element with two classes
提问by FurryWombat
Possible Duplicate:
How to get elements with multiple classes
可能的重复:
如何获取具有多个类的元素
Working on a bit of javascript code that sets the current URL of the referring page to pass into an iframe widget. No control over the code of the page on which the javascript resides, except for the one bit of javascript code.
处理一些 javascript 代码,设置引用页面的当前 URL 以传递到 iframe 小部件。无法控制 javascript 所在页面的代码,除了一位 javascript 代码。
An example of the element value I need to grab is as follows:
我需要抓取的元素值示例如下:
<div id="new_p_2FRolls-Royce_p_2F2013-Rolls-Royce-Phantom_p_2BDrophead_p_2BCoupe-4a5be12c0a0a00650143b598a45df25d_p_2Ehtm" class="page NEW_VEHICLE_DETAILS current">
What I'm trying to do is select the div by combining classes "page" and "current". In this example, "NEW_VEHICLE_DETAILS" is unique to this page, and varies on other pages. I would like to create a consistent bit of code that doesn't have to be altered for each page as it is currently. Here is the code I am using right now:
我想要做的是通过组合类“页面”和“当前”来选择 div。在此示例中,“NEW_VEHICLE_DETAILS”是该页面独有的,在其他页面上有所不同。我想创建一个一致的代码位,不必像当前那样为每个页面进行更改。这是我现在正在使用的代码:
<div id="build_iframe"></div>
<script>
var pageid = document.getElementsByClassName('NEW_VEHICLE_DETAILS')[0].id;
var currenturl = 'http://m.whateverwebsite.com/index.htm#'+pageid;
var shareurl = escape(currenturl);
document.getElementById('build_iframe').innerHTML = '<iframe style="border:1px;width:100%;height:110px;" src="http://widget.mywidgetwebsite.com/share-tool/?current_url='+shareurl+'"></iframe>';
</script>
jQuery is not an option in this case. How can I get the value of the ID by selecting only the element with BOTH "page" and "current" classes set?
在这种情况下,jQuery 不是一个选项。如何通过仅选择同时设置“页面”和“当前”类的元素来获取 ID 的值?
回答by James Allardice
You could use querySelector
(or querySelectorAll
if there's more than one matching element and you want to get a reference to all of them):
您可以使用querySelector
(或者querySelectorAll
如果有多个匹配元素并且您想获得对所有元素的引用):
var elem = document.querySelector(".page.current");
You can also actually just use getElementsByClassName
, which accepts a space-separated list of class names:
您实际上也可以只使用getElementsByClassName
,它接受以空格分隔的类名列表:
var elems = document.getElementsByClassName("page current");