Using classlist.contains on Multiple Elements


#1

This is a response to a comment on how to use the classList.contains method to check for the existence of multiple classes. Since this isn’t built-in to the classList API directly, I threw this together quickly:

DOMTokenList.prototype.containsMany = function(classes) {
  var items = classes.split(' ');

  for (var i = 0; i < items.length; i++) {
    var item = items[i];

    if (this.contains(item) == false) {
      return false;
    }
  }

  return true;
}

To test this out, I used the following HTML:

<div class="batman joker bain riddler batgirl robin alfred"></div>

And this was the JS that put it all to good use:

var el = document.querySelector("div");
var test = el.classList.containsMany("batman kirupa robin");
document.writeln(test);

I tried a few variations, and it all seemed to work. If you run into a breaking case, let me know and I can try to fix it quickly :smile:

Cheers,
Kirupa


#2

I’d just see what jQuery does differently, then see if that suggests any error cases.


#3

I looked at it, but I couldn’t see any differences. Since I am relying on classList under the covers for my implementation, I’m hoping that any issues would be with classList and not with what I have going haha. Also, that JS formatting with that many spaces is something I haven’t encountered before!

:elephant:


#4

I think that’s just how monospace tabs render in HTML.


#5
// author Fedor Vlasenko [email protected]
const containsMany = (el, classes) => Array.isArray(classes) && !!classes.length && classes.every(cls => el.classList.contains(cls));
let el = document.querySelector("div");
let test1 = containsMany(el, ["batman", "kirupa", "robin"]);
let test2 = containsMany(el, ["batman", "alfred", "robin"]);
let test3 = containsMany(el, []);
let test4 = containsMany(el, [""]);
let test5 = containsMany(el);
let test6 = containsMany(el, "batman");
document.writeln("test1: " , test1 ,"<br>");
document.writeln("test2: " , test2 ,"<br>");
document.writeln("test3: " , test3 ,"<br>");
document.writeln("test4: " , test4 ,"<br>");
document.writeln("test5: " , test5 ,"<br>");
document.writeln("test6: " , test6 ,"<br>");