George Katsanos
George Katsanos

Reputation: 14195

manipulate querySelectorAll elements without looping over the NodeList

With jQuery it's possible to use the addClass / removeClass / toggleClass methods to manipulate classes.

We can do similar things the new native Node methods - using classList - but one problematic situation is when we need to make manipulations to a set of elements.

How would a method which abstracts the looping look like so we don't need to convert the NodeList returned by querySelectorAll into an Array and forEach it every time manually?

e.g. :

const tableRows = [...document.querySelectorAll('table tbody tr')];
tableRows.forEach((element) => {
  // do stuff for every element here
});

My solution to that was

Array.prototype.addClass = function (className) {
  this.forEach((element) => {
    element.classList.add(className);
  });
};

Array.prototype.removeClass = function (className) {
  this.forEach((element) => {
    element.classList.remove(className);
  });
};

but adding methods on the prototype isn't a good idea.

Upvotes: 0

Views: 668

Answers (1)

Dekel
Dekel

Reputation: 62676

Even with jQuery - under the hood, it does exactly the same.
A jQuery object has a list of all the DOM elements, and when you call a method on the jQuery's object - it loops over all the DOM elements and call that specific method on the DOM element.

Check this for example:
https://github.com/jquery/jquery/blob/master/src/attributes/classes.js#L29

Eventually - it's the same.

Note that jQuery does more things, so if you are looking at efficiency - probably a code that you will write will be a bit more efficient (in case you are talking about looping a list of elements in order to add/remove classes).

Upvotes: 1

Related Questions