Select and add class in javascript

笑着哭i 提交于 2019-12-03 03:12:20

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

Using some newer browser objects and methods.

Pure JS: Details: old fashioned way, declaring stuff at the beginging than iterating in one big loop over elements with index 'i', no big science here. One thing is using classList object which is a smart way to add/remove/check classes inside arrays.

var elements = document.querySelectorAll('.even','.odd'),
    i, length;

for(i = 0, length = elements.length; i < length; i++) {
    elements[i].classList.add('cf');
}

Pure JS - 2: Details: document.querySelectorAll returns an array-like object which can be accessed via indexes but has no Array methods. Calling slice from Array.prototype returns an array of fetched elements instantly (probably the fastest NodeList -> Array conversion). Than you can use a .forEach method on newly created array object.

Array.prototype.slice.call(document.querySelectorAll('.even','.odd'))
 .forEach(function(element) {
    element.classList.add('cf');
});

Pure JS - 3: Details: this is quite similar to v2, [].map is roughly that same as Array.prototype.map except here you declare an empty array to call the map method. It's shorter but more (ok little more) memory consuming. .map method runs a function on every element from the array and returns a new array (adding return in inside function would cause filling the returned values, here it's unused).

[].map.call(document.querySelectorAll('.even','.odd'), function(element) {
    element.classList.add('cf');
});

Pick one and use ;)

querySelectorAll is supported in IE8, getElementsByClassName is not, which does not get two classes at the same time either. None of them work in iE7, but who cares.

Then it's just a matter of iterating and adding to the className property.

var list = document.querySelectorAll(".even, .odd");
for (var i = list.length; i--;) {
    list[i].className = list[i].className + ' cf';
}

FIDDLE

As others mention for selecting the elements you should use .querySelectorAll() method. DOM also provides classList API which supports adding, removing and toggling classes:

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

As always IE9 and bellow don't support the API, if you want to support those browsers you can use a shim, MDN has one.

I know this is old, but is there any reason not to simply do this (besides potential browser support issues)?

document.querySelectorAll("li.even, li.odd").forEach((el) => {
    el.classList.add('cf');
});

Support: https://caniuse.com/#feat=es5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!