如何通过 HTMLCollection 上的类名获取元素

Sah*_*and 5 javascript

我一直在思考为什么我们不能在 javascript 中做到这一点。

document.getElementsByClassName('class1').getElementsByClassName('class2')
Run Code Online (Sandbox Code Playgroud)

这是行不通的,因为第一次getElementsByClassName调用会给我们一个 HTMLCollection,它没有getElementsByClassName定义。为什么是这样?以这种方式使用这将是一个很好的函数,因为它可以让您基于具有多个不同类而不只是一个类的元素来获取元素。

有没有什么办法:

  1. 在 HTMLCollection 中按类名获取元素
  2. 通过多个类名获取元素

小智 6

通过多个类名获取:

document.querySelector('.someclass.otherclass'); // get first element that matches
document.querySelectorAll('.someclass.otherclass'); //get all elements that match
Run Code Online (Sandbox Code Playgroud)

您可以querySelector*在任何 DOM 元素(而不仅仅是 )document中进行搜索。

通过 HTMLCollection 中的类名获取

[].filter.call(
    htmlCollection, element => [].includes.call(elements.classList, 'someclassname')
)
Run Code Online (Sandbox Code Playgroud)

HTMLCollection 和数组都不是.classList数组,而只是类似数组的对象,因此需要.call.


kar*_*ael 1

  1. 通过 HTMLCollection 中的类名获取元素:

    HTMLCollection.prototype.forEach = Array.prototype.forEach;
    
    HTMLCollection.prototype.getElementsByClassName = function( name ){
        var all = [];
        this.forEach( function( el ){
             if( el )
                 all.concat( el.getElementsByClassName( name ) );
        });
        return all;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 通过多个类名获取元素:

    document.querySelectorAll('.class1.class2');
    
    Run Code Online (Sandbox Code Playgroud)

请使用第二个以获得更好的性能。