JavaScript按类名获取所有元素,同时排除特定类?

Non*_*niq 3 html javascript

所以我想说我有以下网站:

<div class="hello"></div>
<div class="hello"></div>
<div class="hello world"></div>
<div class="hello"></div>
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我将所有具有"hello"类的元素保存到数组中:

var inputs = document.getElementsByClassName('hello');

有什么方法可以排除所有具有"世界"类的元素,所以我只能获得三个结果吗?

Dav*_*mas 10

从理论上讲,你可以使用 document.querySelectorAll()

// searches for all <div> elements with the class of 'hello',
// and without the class of 'world':
var inputs = document.querySelectorAll('div.hello:not(.world)');
Run Code Online (Sandbox Code Playgroud)

var inputs = document.querySelectorAll('div.hello:not(.world)');
console.log(inputs);
Run Code Online (Sandbox Code Playgroud)
<div class="hello"></div>
<div class="hello"></div>
<div class="hello world"></div>
<div class="hello"></div>
Run Code Online (Sandbox Code Playgroud)

或者您可以简单地将其NodeList转换为数组,并过滤​​该数组:

// searches for all elements with the class-name of 'hello':
var inputs = document.getElementsByClassName('hello'),

    // Array.prototype.slice.call(inputs,0) uses the Array
    // method of slice on the NodeList returned by
    // document.getElementsByClass(), turning it into an
    // Array:
    inputsArray = Array.prototype.slice.call(inputs, 0)
                    // then we filter the Array:
                    .filter(function (el) {
                      // el: a reference to the current
                      //     Array element of the Array
                      //     over which we're iterating.

      // el.classList.contains returns a Boolean
      // true if the 'el' contains a class of
      // 'world', and false if not; we invert that
      // using the ! (not) operator because
      // Array.prototype.filter() retains elements
      // should the evaluation be true/truthy;
      // whereas we want to keep the elements for
      // which classList.contains() is false:
      return !(el.classList.contains('world'));
    });
Run Code Online (Sandbox Code Playgroud)

var inputs = document.getElementsByClassName('hello'),
  inputsArray = Array.prototype.slice.call(inputs, 0).filter(function(el) {
    return !(el.classList.contains('world'));
  });

console.log(inputsArray);
Run Code Online (Sandbox Code Playgroud)
<div class="hello"></div>
<div class="hello"></div>
<div class="hello world"></div>
<div class="hello"></div>
Run Code Online (Sandbox Code Playgroud)


Dan*_*ite 10

使用querySelectorAll.

var inputs = document.querySelectorAll('.hello:not(.world)')
Run Code Online (Sandbox Code Playgroud)