classList
is a JavaScript property that can be used to work with CSS classes on HTML elements, useful to add, remove, replace and toggle CSS classes on an element. It contains an object list of the class attribute.
Syntax:
class
attribute is not set or is empty, the element.classList.length
returns 0.The object contained by the classList
property has these methods:
add(class1, class2, ..)
- adds one or more class names to an element. If the specified class already exist, the class will not be added.contains(class)
- To check if an element contains or not a specified css class. It returns True if the element contains the specified class name; otherwise, False.item(index)
- returns the class name with a specified index number (index starts at 0), or Null if the specified index is out of range.remove(class1, class2, ..)
- removes one or more class names from an element.replace(oldClass, newClass)
- replaces an existing class with a new class.toggle(class, [true|false])
- When only one argument is passed: Toggle class value, if class exists then remove it and return false, if not, then add it and return true.element.classList.toggle('classToRemove', false);- Add a class:
element.classList.toggle('classToAdd', true);
1. Adds two css classes to a <div>:
var div1 = document.getElementById('div1'); div1.classList.add('cls_1', 'cls_2');
2. Removes a css class from a <div>:
var div1 = document.getElementById('div1'); div1.classList.remove('cls_2');
3. Checks if a <div> contains or not a specified css class:
var div1 = document.getElementById('div1'); if(div1.classList.contains('cls_1')) alert('.cls_1 in #div1'); else alert('.cls_1 not in #div1');
4. Replaces class 'foo' with 'bar':
var div1 = document.getElementById('div1'); div1.classList.replace('foo', 'bar');
5. If 'visible' is set removes it, otherwise add it:
var div1 = document.getElementById('div1'); div1.classList.toggle('visible');
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net