Select and add class in javascript

Yannis Dran picture Yannis Dran · Jan 23, 2014 · Viewed 42.8k times · Source

Cross Platform if possible, how can I select classes in Javascript (but not Jquery please -MooTools is fine though-) on code that I can't add an ID? Specifically, I want to add the class "cf" on any li below:

HTML

<div class="itemRelated">
  <ul>
<li class="even">
<li class="odd">
<li class="even">

I tried to fiddle it but something is missing:

Javascript

 var list, i;
list = document.getElementsByClassName("even, odd");
for (i = 0; i < list.length; ++i) {
    list[index].setAttribute('class', 'cf');
}

JSFiddle

ps. This question phenomenally has possible duplicates, (another one) but none of the answers makes it clear.

Answer

Sergio picture Sergio · Jan 23, 2014

Using plain javascript:

var list;
list = document.querySelectorAll("li.even, li.odd");
for (var i = 0; i < list.length; ++i) {
   list[i].classList.add('cf');
}

Demo

For older browsers you could use this:

var list = [];
var elements = document.getElementsByTagName('li');
for (var i = 0; i < elements.length; ++i) {
    if (elements[i].className == "even" || elements[i].className == "odd") {
        list.push(elements[i]);
    };
}
for (var i = 0; i < list.length; ++i) {
    if (list[i].className.split(' ').indexOf('cf') < 0) {
        list[i].className = list[i].className + ' cf';
    }
}

Demo


Using Mootools:

$$('.itemRelated li').addClass('cf');

Demo

or if you want to target specific by Class:

$$('li.even, li.odd').addClass('cf');

Demo