选择具有两个类的元素 [英] Select element with two classes

查看:93
本文介绍了选择具有两个类的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何获取具有多个类的元素

使用一些javascript代码设置引用页面的当前URL以传递到iframe小部件。无法控制javascript所在页面的代码,除了一点javascript代码。

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.

我需要抓取的元素值的一个示例是as如下:

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">

我要做的是通过组合page和current类来选择div 。在此示例中,NEW_VEHICLE_DETAILS对于此页面是唯一的,并且在其他页面上有所不同。我想创建一个一致的代码,不必像现在这样对每个页面进行更改。以下是我现在使用的代码:

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 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不是一个选项。如何通过仅选择设置了页面和当前类的元素来获取ID的值?

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?

推荐答案

您可以使用 querySelector (或 querySelectorAll 如果有多个匹配元素,并且您想获得对所有匹配元素的引用):

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):

var elem = document.querySelector(".page.current");

您实际上也可以使用 getElementsByClassName ,它接受以空格分隔的类名列表:

You can also actually just use getElementsByClassName, which accepts a space-separated list of class names:

var elems = document.getElementsByClassName("page current");

这篇关于选择具有两个类的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆