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/
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
{} 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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With