Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and add class in javascript

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.

like image 774
Yannis Dran Avatar asked Jan 23 '14 21:01

Yannis Dran


People also ask

Can you add a class in JavaScript?

In JavaScript, there are some approaches to add a class to an element. We can use the . className property or the . add() method to add a class name to the particular element.

Can you select by class in JavaScript?

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.


1 Answers

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

like image 96
Sergio Avatar answered Oct 07 '22 14:10

Sergio