Javascript getElementsByClassName() 有两个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37255293/
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 20:05:36  来源:igfitidea点击:

getElementsByClassName() with two classes

javascripthtmldom

提问by Unknown developer

Is it possible to get all elements with class aorbusing getElementsByClassName()only once? I'd prefer vanilla JavaScript.

是否可以使用类ab使用getElementsByClassName()一次来获取所有元素?我更喜欢香草 JavaScript。

回答by Pranav C Balan

You can't do it with getElementsByClassName()method instead use querySelectorAll()method with comma separated class selectors.

您不能使用getElementsByClassName()方法来实现,而是使用querySelectorAll()带有逗号分隔的类选择器的方法。

document.querySelectorAll('.a,.b')

回答by Pointy

You canpass more than one class name to getElementsByClassName()by separating them with spaces:

可以通过getElementsByClassName()用空格分隔传递多个类名:

var elems = document.getElementsByClassName("class1 class2 class3");

Now, this differs from the .querySelectorAll(".class1,.class2,.class3")approach in that it applies a conjunction, not a disjunction— "and" instead of "or". Thus

现在,这与.querySelectorAll(".class1,.class2,.class3")方法的不同之处在于它应用了连词,而不是析取——“and”而不是“or”。因此

var elems = document.getElementsByClassName("class1 class2 class3");

is like

就好像

var elems = document.querySelectorAll(".class1.class2.class3");

Sometimes you want one, sometimes you want the other. It's definitely true that .querySelectorAll()gives you much more flexibility.

有时你想要一个,有时你想要另一个。这绝对是正确的,它.querySelectorAll()为您提供了更多的灵活性。

回答by Micha? Per?akowski

No, you can't achieve that with only one document.getElementsByClassName()call. That function returns elements which have allof the classes specified in the first argument as a space-separated string.

不,你不能只通过一个document.getElementsByClassName()电话来实现这一点。该函数返回具有第一个参数中指定的所有类的元素作为空格分隔的字符串。

There are two possible solution. First is to use document.querySelectorAll()instead, which uses CSS selectors.

有两种可能的解决方案。首先是使用document.querySelectorAll(),它使用 CSS 选择器。

document.querySelectorAll(".a, .b")

The second solution is to call document.getElementsByClassName()twice, turn the results into arrays using Array.from()and merge them using Array.prototype.concat(). To avoid duplicates (for example when element has bothaand bclass), you have to create a new Setfrom that array, and then turn it back to array using Array.from().

第二种解决方案是调用document.getElementsByClassName()两次,使用将结果转换为数组Array.from()并使用将它们合并Array.prototype.concat()。为了避免重复(例如,当元素有两个ab类),你必须创建一个新的集合从数组,然后使用重新设置为阵列Array.from()

const classA = Array.from(document.getElementsByClassName("a"))
     ,classB = Array.from(document.getElementsByClassName("b"))
     ,result = Array.from(new Set(classA.concat(classB)))

See demo below:

请参阅下面的演示:

console.log("first solution", document.querySelectorAll(".a, .b"))

const classA = Array.from(document.getElementsByClassName("a"))
     ,classB = Array.from(document.getElementsByClassName("b"))
     ,result = Array.from(new Set(classA.concat(classB)))

console.log("second solution", result)
<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>
<div class="c"></div>

Note that the first solution gives an array-like NodeListobject, whereas the second gives just an array.

请注意,第一个解决方案给出了一个类似数组的NodeList对象,而第二个解决方案只给出了一个数组。

回答by zoubida13

Just to add a bit more support, here is a version that is compatible with older versions of IE and uses pure vanilla js :

只是为了添加更多支持,这里有一个与旧版本 IE 兼容并使用纯 vanilla js 的版本:

function getElementsByClassNameOr(root, classNameString) // classNameString like '.a, .b' don't forget the comma separator
 {
    var arr = [],
    rx = new RegExp('(^|[ \n\r\t\f])' + classNameString + '([ \n\r\t\f]|$)'),
    elements = root.getElementsByTagName("*");

    var elem;

    for (i=0 ; i < elements.length ; i++) {
        elem = elements[i];
        if (rx.test(elem.className)) {
            arr.push(elem);
        }

    }

    return arr; // will contain all the elements that have one of the classes in ClassNameString, root can be document or a div.
}