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

时间:2016-08-05 11:52:38

标签: javascript html

所以,让我们说我有以下网站:

<div class="hello"></div>
<div class="hello"></div>
<div class="hello world"></div>
<div class="hello"></div>

使用以下代码,我保存所有具有类&#34; hello&#34;的元素。成阵列:

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

我有什么方法可以排除所有拥有该类&#34; world&#34;所以我只能得到三个结果?

2 个答案:

答案 0 :(得分: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)');

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

或者您可以简单地将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'));
    });

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

console.log(inputsArray);
<div class="hello"></div>
<div class="hello"></div>
<div class="hello world"></div>
<div class="hello"></div>

答案 1 :(得分:9)

使用querySelectorAll

var inputs = document.querySelectorAll('.hello:not(.world)')