Element.classList
jest właściwością tylko do odczytu, która zwraca zbiór live DOMTokenList
atrybutów klasy danego elementu.
Używanie classList
stanowi wygodną alternatywę uzyskiwania dostępu do listy klas danego elementu w formie skompresowanego stringa poprzez element.className
.
Składnia
const elementClasses = elementNodeReference.classList;
elementClasses to DOMTokenList reprezentujący atrybuty klasy elementNodeReference. Jeśli atrybut klasy nie został określony lub jest pusty, elementClasses.length zwraca 0. Sam w sobie element.classList
jest tylko do odczytu, ale można go mimo to modyfikować poprzez stosowanie metod add()
i remove()
.
Metody
- add( String [, String] )
- Nadaje określone wartości klasy. Jeśli wartości te już istnieją w atrybucie elementu, wówczas zostają zignorowane.
- remove( String [,String] )
- Usuwa określone wartości klasy.
- item ( Number )
- Zwraca wartosć klasy wg indeksu w zbiorze.
- toggle ( String [, force] )
- Jeśli występuje tylko jeden argument: Przełącza wartość klasy, tzn. jeśli klasa istnieje, wówczas zostaje usunięta i zwraca
false
, jeśli nie, wówczas dodaje ją i zwracatrue
.
Jeśli występuje również drugi argument: Jeśli drugi argument uznawany jest za true, dodaje określoną wartość klasy, natomiast jeśli zostaje uznany za false, wówczas zostaje usunięty. - contains( String )
- Sprawdza, czy określona wartość klasy istnieje w atrybucie klasy danego elementu.
Przykłady
// div jest obiektem odwołującym się do elementu <div> o klasie ="foo bar"
div.classList.remove("foo");
div.classList.add("anotherclass");
// jeśli ustawiona jest widoczność usuwa ją, w przeciwnym wypadku dodaje
div.classList.toggle("visible");
// dodaj/usuń (add/remove) jest widoczne, w zależności od warunku testowego, i mniejsze od 10
div.classList.toggle("visible", i < 10 );
alert(div.classList.contains("foo"));
// dodaj lub usuń złożone klasy
div.classList.add("foo", "bar");
div.classList.remove("foo", "bar");
Wersje Firefoxa wcześniejsze niż 26 nie implementują użycia niektórych argumentów metod dodaj/usuń/przełącz (add/remove/toggle). Zobacz https://bugzilla.mozilla.org/show_bug.cgi?id=814014
Polyfill
// Źródło: https://gist.github.com/k-gun/c2ea7c49edf7b757fe9561ba37cb19ca
;(function() {
// pomocnicy
var regExp = function(name) {
return new RegExp('(^| )'+ name +'( |$)');
};
var forEach = function(list, fn, scope) {
for (var i = 0; i < list.length; i++) {
fn.call(scope, list[i]);
}
};
// obiekt listy klasy z podstawowymi metodami
function ClassList(element) {
this.element = element;
}
ClassList.prototype = {
add: function() {
forEach(arguments, function(name) {
if (!this.contains(name)) {
this.element.className += this.element.className.length > 0 ? ' ' + name : name;
}
}, this);
},
remove: function() {
forEach(arguments, function(name) {
this.element.className =
this.element.className.replace(regExp(name), '');
}, this);
},
toggle: function(name) {
return this.contains(name)
? (this.remove(name), false) : (this.add(name), true);
},
contains: function(name) {
return regExp(name).test(this.element.className);
},
// bonus..
replace: function(oldName, newName) {
this.remove(oldName), this.add(newName);
}
};
// IE8/9, Safari
if (!('classList' in Element.prototype)) {
Object.defineProperty(Element.prototype, 'classList', {
get: function() {
return new ClassList(this);
}
});
}
// replace() wspierane przez pozostałe przeglądarki
if (window.DOMTokenList && DOMTokenList.prototype.replace == null) {
DOMTokenList.prototype.replace = ClassList.prototype.replace;
}
})();
Specyfikacje
Specifikacja | Status | Komentarz |
---|---|---|
HTML Living Standard The definition of 'Element.classList' in that specification. |
Living Standard | Note within the HTML specification related to the class attribute. |
DOM The definition of 'Element.classList' in that specification. |
Living Standard | Initial definition |
DOM4 The definition of 'Element.classList' in that specification. |
Obsolete |
Zgodność z przeglądarkami
Cecha | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|---|
Zgodność podstawowa | 8 | 12 | 3.6 (1.9.2) | 10[1] | 11.50 | 5.1 |
toggle() method's second argument |
24 | 12 | 24 (24) | No support[2] | 15 | 7 |
Multiple arguments for add() & remove() |
28 | 12 | 26 (26) | No support | 15 | 7 |
replace() |
No support | ? | 49 (49) | No support | No support | No support |
Cecha | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Wsparcie podstawowe | 3.0 | 12 | 1.0 (1.9.2) | 10[1] | 11.10 | 5.0 |
toggle method's second argument | 4.4 | 12 | 24.0 (24) | No support[2] | ? | 7.0 |
multiple arguments for add() & remove() |
4.4 | 12 | ? | No support | ? | 7.0 |
replace() |
No support | ? | 49 (49) | No support | No support | No support |
[1] Brak wsparcia dla elementów SVG. Zobacz raport w tej kwestii na stronie Microsoftu.
[2] Internet Explorer nigdy tego nie zimplementował. Zobacz raport w tej kwestii na stronie Microsoftu.