JavaScript

[JavaScript] CSS 활용한 스타일 변경(className, classList, .toggle)

개발자 마멋 2023. 11. 11. 09:27

- 자바스크립트에는 애니메이션 기능을, CSS에는 스타일 기능을 쓰는 게 좋다.

- 즉, 구분해서 사용하는 것이 좋음


HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css"> // css 파일과 연결
    <title>valila js</title>
</head>
<body>
    <div class="hello">
    <h1>click me!</h1>
    </div>
    <script src="web.js"></script> // JS 파일과 연결
</body>
</html>

JavaScript에서 조건문 활용한 스타일 변경

const h1 = document.querySelector(".hello:first-child h1");

function handleTitleClick() {
    const currentColor = h1.style.color
    let newColor;
if(currentColor === "blue") {
    newColor = "tomato";
} else {
    newColor = "blue";
}
h1.style.color = newColor;
}

h1.addEventListener("click", handleTitleClick);

 

h1 클릭 시 글자색이 blue이면 tomato로 변경, 그렇지 않다면 blue로 변경


CSS 활용

CSS

body {
    background-color: beige;
}

h1 {
    color: cornflowerblue;
}

.active {
    color: tomato;
}

JavaScript

const h1 = document.querySelector(".hello:first-child h1");

function handleTitleClick() {
    h1.className = "active";
}

h1.addEventListener("click", handleTitleClick);

 

스타일에 관한 것은 CSS에 넣음

1. CSS ➝ .active(class = "active") 색상을 토마토로 설정

2. JS ➝ h1 클릭 시 class가 active가 됨

3. h1 클릭 시 tomato 색상이 됨

 

className

const h1 = document.querySelector(".hello:first-child h1");

function handleTitleClick() {
    const clickedClass = "clicked"; 
    /* law value(clicked) 사용으로 인한 에러 발생 최소화 목적, 변수 사용 시 잘못 적으면 콘솔에서 알려줌 */
    if(h1.className === clickedClass) {
        h1.className = "";
    } else {
        h1.className = clickedClass;
    }
}

h1.addEventListener("click", handleTitleClick);

 

조건문을 활용하여 누를때마다 색상이 바뀌게 설정

 

clickedClass라는 변수를 선언해서 에러 발생 최소화

 

문제점 : h1에 class가 이미 존재한다면 그 class를 없애버림

해결방법 ➝ classList 사용

 

classList

const h1 = document.querySelector(".hello:first-child h1");

function handleTitleClick() {
    const clickedClass = "clicked";
    if(h1.classList.contains(clickedClass)) {
        h1.classList.remove(clickedClass);
    } else {
        h1.classList.add(clickedClass);
    }
}

h1.addEventListener("click", handleTitleClick);

 

classList.contains : HTML 요소의 class에 지정값이 포함되어 있는지 확인

 

만약(if) classList에 "clicked"가 있다면 "clicked"를 제거(remove)하고

그렇지 않다면(else) "clicked"를 추가(add)

 

classList를 사용하면 기존에 존재하던 className 유지 가능

 

classList.toggle

const h1 = document.querySelector(".hello:first-child h1");

function handleTitleClick() {
    h1.classList.toggle("clicked");
}

h1.addEventListener("click", handleTitleClick);

/* 결과 : 위의 조건문을 활용한 classList 예시와 같음 */

 

.toggle : classList에 "clicked"가 있다면 제거하고, 없다면 추가하는 기능을 가진 함수

 

기존에 있던 class 유지 가능

'JavaScript' 카테고리의 다른 글

[노마드 코더] local storage  (1) 2023.11.13
[JavaScript] HTML Value 불러오는 방법  (0) 2023.11.11
[JavaScript] Event  (0) 2023.11.10
[JavaScript] getElements, querySelector 차이  (0) 2023.11.10
let textNodes = document.querySelectorAll("div.tt_article_useless_p_margin.contents_style > *:not(figure):not(pre)"); textNodes.forEach(function(a) { a.innerHTML = a.innerHTML.replace(/`(.*?)`/g, '$1'); });