JS DOM - 02.04 - Class & Atributes

‘className’ & ‘classList’

elem.className corresponds to the class attribute. If something is assigned to elem.className it replaces the whole string of classes. so it operates on the full class string.

The classList is a special object with methods to add/remove/toggle a single class. used to work on individual class.

<body class="main page">

<script>
	alert(document.body.className);  // main page
	
	document.body.classList.add('article');
	alert(document.body.className); // main page article
</script>

Methods of classList:

elem.classList.add/remove("class")
// adds/removes the class.

elem.classList.toggle("class")
// adds the class if it doesn’t exist, otherwise removes it.

elem.classList.contains("class")
// checks for the given class, returns true/false.
div.classList.add("new");
// adds class 'new' to the new div

div.classList.remove("new");
// removes 'new' class from div

div.classList.toggle("active");
// if div doesn't have class 'active' then add it, if it does, then remove it.

classList is iterable, so we can list all classes with for..of

<body class="main page article">

<script>
	for(let name of document.body.classList) {
		alert(name);  // main  page  article
		}
</script>
</body>

Working with classes

It is often standard and cleaner to toggle CSS style rather than adding and removing inline CSS.


Editing HTML attributes

div.setAttribute("id", "theDiv");
// if id exists, update it to 'theDiv', else create an id with value 'theDiv'

div.getAttribute("id");
// returns value of specified attrbute, in this case "theDiv"

div.removeAttribute("id");
// removes specified attribute
// adds several style rules using Element.setAttributes()
div.setAttribute("style", "color: blue; background: white;");
// this takes two arguments, the attribute you want to set and the value.

div.setAttribute("class", "highlight");
// setting a class name of highlight

HTML attributes to check out????