TheRealWazzar
TheRealWazzar

Reputation: 73

JS - Add an array of classes to an element

I decided to take off my jQuery trainer wheels and try some native JS. It's been...educational.

Anyway, here's what I'm trying to emulate:

$('.select_me').addClass('give_me more_classes');

So far, I've figured out how to select elements and add a single class to them. What I'm having trouble with, is using an array to add multiple classes to an element.

Here's what I've tried:

// Select the element
var div = document.querySelector('.select_me');

// Create an array with the classes to add
var classArray = ['give_me', 'more_classes'];

// Apply the new classes.
div.classList.add('just_a_test', 'okay'); // Works, but not what I want.
div.classList.add.apply(null, classArray); // Uncaught TypeError: Illegal invocation

I suspect I'm using apply() wrong, but I'm not yet knowledgeable enough to know how to use it properly. Could one of you fine folk educate me, or point me in the right direction?

JSFiddle:
https://jsfiddle.net/peg8zrw7/2/

Upvotes: 6

Views: 4378

Answers (3)

Sarout
Sarout

Reputation: 902

you can add ... cl inside the parentheses, or you can directly add them like classList.add("ClassOne","ClassTwo","ClassThree"). Mozilla Element.classList

// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

Upvotes: 0

Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

The best way to do more stuff in vanilla JavaScript is to always look at the Mozilla developers site or youmaynotneedjquery

if (el.classList){
  el.classList.add(className);
}else{
  el.className += ' ' + className;
}

This simple statement can be implemented inside a function and create your own library of code to avoid using jQuery.

Upvotes: 0

Lye Fish
Lye Fish

Reputation: 2568

The context of the .add() method is important. Using null won't work because then add will have no idea what to operate on.

Do this instead:

var cl = div.classList;
cl.add.apply(cl, classArray);
// ----------^-- sets the `this` value of the `.add()` method

// Select the element
var div = document.querySelector('.select_me');

// Create an array with the classes to add
var classArray = ['give_me', 'more_classes'];

// Apply the new classes.
var cl = div.classList;
cl.add('just_a_test', 'okay');
cl.add.apply(cl, classArray);
div {
    width: 100px;
    height: 100px;
    background-color: #eeeeee;
}

.select_me.just_a_test.okay {
    border: 2px solid #000000;
}

.select_me.give_me {
    background: #666666;
}

.select_me.more_classes {
    border-radius: 50% 0px 50% 0px;
}
<div class="select_me"></div>


Note that in ECMAScript 6 (and currently in Firefox) you'll be able to do this:

div.classList.add(...classArray);

Upvotes: 15

Related Questions