In this article, I would like to create short reference for how add/remove/toogle
class in pure Javascript and with framework.
Javascript
className
Property className
has value of HTML-atribute class
:
<body class="class1 class2"></body>
console.log(document.body.className);
//class1 class2
document.body.className += ' class3';
console.log(document.body.className);
//class1 class2 class3
classList
Property classList
gives convenient interface for work with certain classes.
elem.classList.contains(cls)
- returntrue/false
if element has classcls
elem.classList.add/remove(cls)
- adding/removing classcls
elem.classList.toogle(cls)
- if element has classcls
, remove it, else add classcls
jQuery
These methods inspect and manpulate classes assigned to elements:
$(elem).hasClass(cls)
- returntrue/false
if element has classcls
$(elem).addClass/removeClass(cls)
- adding/removing classcls
$(elem).toogleClass(cls)
- if element has class(es)cls
, remove it, else add class(es)cls
AngularJS
ng-class
ng-class
accepts an “expression” that must evaluate to one of the following:
- a
string
of space-delimited class names - an
array
of class names - a
map/object
of class names to boolean values
See the Pen AngularJS, ng-class example by qetr1ck-op (@qetr1ck-op) on CodePen.
ng-style
ng-style
accepts an “expression” that must evaluate to:
- an
map/object
of CSS style names to CSS values
See the Pen AngularJS, ng-style example by qetr1ck-op (@qetr1ck-op) on CodePen.