className and classList

Can Avcı
2 min readDec 12, 2022

changing the class one of the most often used methods in js. the elemt.className corresponds to the “class” attribute

<body class="main page">
<script>
alert(document.body.className); // main page
</script>
</body>

if we assign something to elem.className. it replace the whole string of classes. sometimes that is what we need. from time to time we want to add/remove a single class rather than completely changing.

the elem.classList is a special object with methods to add/remove/toggle a single class.

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

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.

Besides, classList is iterable, so we can list all classes with for..of, like this:

<body class="main page">
<script>
for (let name of document.body.classList) {
alert(name); // main, and then page
}
</script>
</body>

Element style

The property elem.style is an object that corresponds to what’s written in the "style" attribute . Setting elem.style.width="100px" works the same as if we had in the attribute style a string width:100px.

Also there is a special method for that, elem.style.removeProperty('style property'). So, We can remove a property like this:

document.body.style.background = 'red'; //set background to red

setTimeout(() => document.body.style.removeProperty('background'), 1000);

modifying a style is easy. But how to read it?
For instance, we want to know the size, margins, the color of an element. How to do it?
So we can’t read anything that comes from CSS classes using elem.style

There’s another method for that: getComputedStyle.

<head>
<style> body { color: red; margin: 5px } </style>
</head>
<body>
<script>
let computedStyle = getComputedStyle(document.body);
// now we can read the margin and the color from it
alert( computedStyle.marginTop ); // 5px
alert( computedStyle.color ); // rgb(255, 0, 0)
</script>
</body>

--

--