Javascript Course


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:
element.classList
- If the class attribute is not set or is empty, the element.classList.length returns 0.

classList Methods

The object contained by the classList property has these methods:

Examples with classList

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');

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="http://coursesweb.net/" title="CoursesWeb.net">CoursesWeb.net</a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
  font-family:"Calibri",sans-serif;
}
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
alert(nr_elms);
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr =[1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
classList - Working with CSS classes

Last accessed pages

  1. Learning Vue.js - Tutorials (1049)
  2. Objects in 3D Space (2035)
  3. Star shapes with CSS (11300)
  4. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (143446)
  5. Callback Functions in JavaScript (1140)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (679)
  2. CSS cursor property - Custom Cursors (87)
  3. Read Excel file data in PHP - PhpExcelReader (59)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (58)
  5. The Mastery of Love (57)