classList.add & remove & toggle

소바·2022년 8월 16일
0

왜 JS를 이용하여 stylesheet를 바꿀까?

not good practice because we're changing the style of each element using Javascript all of our styles should actually be inside our CSS. But the problem is that if we wanted our style to change on the fly, say if a user clicks on a button then the color of the background changes,

for example, if we query for our button and we tap into its classList property, then you can see that it gives us a list of the classes that are attached to this element that we found.

once we have the list of classes, then we can use methods, for example .add, and we can add classes to the class list.

document.querySelector.classList.add

this way we can keep all of our styles still inside our style sheet but we can turn it on and off using JS

document.querySelector.classList.remove

I can simply remove that invisible class and all of the styles that are associated with that class gets

document.querySelector.classList.toggle

if the class invisible is already applied then remove it, and if it's not applied then apply it. now if I just keep using toggle you can see our button comes on and off and on and off.

정리

styles got applied to it just by using a single line of Javascript and keeping our code separated so that our style is still in our stylesheet and our behavior is still in our Javascript.

출처 : 유데미 강좌 (Dr. Angela Yu Developer and Lead Instructor)

profile
소바보이

0개의 댓글