Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Add an array of classes to an element

Tags:

javascript

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/

like image 918
TheRealWazzar Avatar asked Apr 03 '15 02:04

TheRealWazzar


People also ask

How do you add classes to elements?

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").

What is {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

How do you add an element to an array of arrays?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.


1 Answers

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);
like image 153
Lye Fish Avatar answered Oct 26 '22 08:10

Lye Fish