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

6

假设我有以下网站:

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

使用以下代码,我将所有具有“hello”类的元素保存到一个数组中: var inputs = document.getElementsByClassName('hello'); 是否有办法排除所有具有“world”类的元素,以便只获取三个结果?
2个回答

16
理论上,您可以使用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>


11

使用querySelectorAll

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

你的意思是querySelectorAll吗? - evilive
@evilive 感谢并已进行修正。 - Daniel A. White

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接