Exceptions when working with attributes in JavaScript
There is an exception when working with
attributes - this is the attribute
class.
This word is special in JavaScript and
therefore we cannot simply write
elem.class to read the value of
the class attribute. Instead,
write elem.className.
Let's look at an example. Let's say we have this input:
<input id="elem" class="aaa bbb">
Let's output the value of the class
attribute for our input:
let elem = document.querySelector('#elem');
console.log(elem.className); // shows 'aaa bbb'
There are other exceptions, such as
the for attribute. It should
be accessed via htmlFor.
A div is given:
<div id="elem" class="content no-gap"></div>
There is also a button. By clicking on
the button, read and display the value
of the class attribute of our div.
A div is given:
<div id="elem"></div>
There is also a button. By pressing the
button, write some class into the
class attribute of our div.
Given a div with several CSS classes separated by spaces:
<div id="elem" class="aaa bbb ccc"></div>
There is also a button. On button click, get an array of CSS classes of our div.