본문 바로가기

JavaScript

[JS] DOM이란? #4 CSS style, class 제어

1. Style제어

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome</title>
  </head>
  <body>
    <div id="box">BOX</div>
    <ul>
      <li>Red</li>
      <li>Green</li>
      <li>blue</li>
    </ul>
    <script>
      const box = docunment.getElementById("box");
      box.style.backgroundColor = "red";
      box.style.color = "#fff";
      box.style.width = "100px";
      box.style.height = "100px";
    </script>
  </body>
</html>

일반적으로는 background-color 라고 적지만 여기에서는 backroundColor라고 명시한다.

만일, 익숙한 방식으로 하고싶다면 대괄호를 써도 된다.

 

ex)  box.style["margin-left"] = "30px";

 

 

 

여러 속성 동시에 적어주는 단축속성도 문자열로 적어주면된다.

ex)  box.style.border = "10px solid #000"

 

 


2. Class제어

  <style>
    .box {
      width: 100px;
      height: 100px;
      border: 4px solid #000;
    }
    .bg-red {
      background-color: #f00;
    }
    .bg-green {
      background-color: #0f0;
    }
    .bg-blue {
      background-color: #00f;
    }
    .txt-yellow {
      color: #ff0;
    }
    .txt-pink {
      color: pink;
    }
  </style>
//콘솔창
box.className;

' '
box.className = 'bg-red';
<'br-red

결과



box.className = 'txt-pink';
<txt-pink

결과

 

 

텍스트를 pink로 주면 배경색이 사라진다. 따라서 같이 적어준다.
//콘솔창
box.className = 'bg-blue txt-pink';

결과

 

 

문제점

실제 프로젝트에서 클래스 갯수가 많을 경우, 어떤 클래스가 있는지 파악하고 추가하고 수정할대마다 다시 적어줘야한다. 그래서 className은 잘 사용하지 않는다. 그 대신

 

classList를 사용한다.

:classlist의 좀 더 자세한 설명이 적혀있는 블로그를 참조함.

 

 

배열처럼 보이는게 나오고 그밑에 class 2개를 보여준다. (box, bg-red)

 

DOMTokenList객체는 메서드들을 제공한다.

 

 

 

자주 사용하는 메서드

메서드(Method) Console에 입력 결과
add
:class를 추가
box.classList.add('txt-white');


- html문서에 가서 보면 txt-white가 추가된 것 확인 가능 (아래참고)



remove
:class를 제거
box.classList.remove('txt-white');


-html문서에서 txt-white가 빠진 것 확인 가능



여러개 삭제 시 쉼표로 구분해준다.

box.classList.remove('bg-green', 'txt-yellow');
replace
:class를 바꿈
box.classList.replace('bg-red', 'bg-blue');
  해석: bg-red를 bg-blue로 바꾼다.

toggle
:해당 class가 있으면 넣어주고 없으면 제거하는 기능
setInterval(()=>{
box.classList.toggle('bg-red');
}, 1000)

*setInterval : 1초에 한번씩 반복한다

 

<script>
const box = document.getElementById("box");
const color = document.getElementById("color");

color.onclick = function (e) { // color=ul. ul의 특정 요소를 클릭했을 때
const target = e.target;
if (target.tagName !== "LI") return; // (이어서)LI가 아니면 return하고
target.classList.toggle("txt-pink"); // (이어서)LI면 classList에 ,toggle 메서드를 이용해 txt-pink라는 class를 없으면 넣고 있으면 제거하는 기능
};
</script>

 

 

 

참고:

https://velog.io/@hovelopin/JS-DOM-%EC%A0%9C%EC