JS: How class list works

Hello World! New episode of the series – A CSS/JS trick in 5 minutes.
Today we will quickly see how to manipulate a class throw javascript (add, remove and check presence).

In reality, you have to imagine classes as a list, all elements in a page…

Hello World! New episode of the series – A CSS/JS trick in 5 minutes.
Today we will quickly see how to manipulate a class throw javascript (add, remove and check presence).

In reality, you have to imagine classes as a list, all elements in a page have is own list of class you can modify with javascript. So if you want to modify an element you don’t need to do all the stuff (it’s much longer and boring) with javascript. You just have to define a class in CSS with all the attributes then add this class to the element(s) you want to modify. So for example you can have a live element update on scrolling



Add

  let foo = document.querySelector("#foo");
  element.classList.add("newClass");
Enter fullscreen mode

Exit fullscreen mode



Remove

 foo.classList.remove("classToRemove");
Enter fullscreen mode

Exit fullscreen mode



You can also check if an element contains a class (and then perform operations with the boolean result):

  foo.classList.contains('AreYouHere')
Enter fullscreen mode

Exit fullscreen mode

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue 🙂


Print Share Comment Cite Upload Translate
APA
DevLorenz0 | Sciencx (2024-03-28T16:18:34+00:00) » JS: How class list works. Retrieved from https://www.scien.cx/2021/02/10/js-how-class-list-works/.
MLA
" » JS: How class list works." DevLorenz0 | Sciencx - Wednesday February 10, 2021, https://www.scien.cx/2021/02/10/js-how-class-list-works/
HARVARD
DevLorenz0 | Sciencx Wednesday February 10, 2021 » JS: How class list works., viewed 2024-03-28T16:18:34+00:00,<https://www.scien.cx/2021/02/10/js-how-class-list-works/>
VANCOUVER
DevLorenz0 | Sciencx - » JS: How class list works. [Internet]. [Accessed 2024-03-28T16:18:34+00:00]. Available from: https://www.scien.cx/2021/02/10/js-how-class-list-works/
CHICAGO
" » JS: How class list works." DevLorenz0 | Sciencx - Accessed 2024-03-28T16:18:34+00:00. https://www.scien.cx/2021/02/10/js-how-class-list-works/
IEEE
" » JS: How class list works." DevLorenz0 | Sciencx [Online]. Available: https://www.scien.cx/2021/02/10/js-how-class-list-works/. [Accessed: 2024-03-28T16:18:34+00:00]
rf:citation
» JS: How class list works | DevLorenz0 | Sciencx | https://www.scien.cx/2021/02/10/js-how-class-list-works/ | 2024-03-28T16:18:34+00:00
https://github.com/addpipe/simple-recorderjs-demo