5

So let's say I have the following website:

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

Using the following code, I save all elements that have the class "hello" into an array:

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

Is there any way I can exclude all elements that have the class "world" so I can only get three results?

Noniq
  • 199
  • 4
  • 12

2 Answers2

14

Theoretically you can use 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>

Or you can simply convert the NodeList into an array, and filter that array:

// 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>
David Thomas
  • 240,457
  • 50
  • 366
  • 401
11

Use querySelectorAll.

var inputs = document.querySelectorAll('.hello:not(.world)')
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430