티스토리 뷰

html 요소에 style과 class를 제어해 보겠습니다.

const box = document.getElementById("box");
box.style.backgroundColor = 'red';
box.style.color = '#fff';
box.style.width = '100px';
box.style.height = '100px';

주의할 점은 일반적으로 css를 작성할 때 background-color 이런식으로 작성을 하는데 여기서는 backgroundColor 이런식으로 카멜케이스로 작성하면 됩니다.

box.style['margin-left'] = '30px';

익숙한 방법으로 작성을 하려면 이런식으로 작성하면 됩니다.

box.style;
CSSStyleDeclaration {...}

box.style 하면 CSSStyleDeclaration이라는 객체가 나오고 많은 스타일들을 볼 수 있고 이 스타일들을 카멜케이스로 작성되어 있습니다.

box.style.border = "10px solid #000";

여러 속성을 동시에 적어주는 단축 속성도 그냥 문자열로 작성하면 됩니다.

.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-white{
	color: #fff;
}
.txt-yellow{
	color: #ff0;
}
.txt-pink{
	color: pink;
}
box.className = 'bg-red'; // 배경색을 red로 변경
box.className = 'bg-blue'; // 배경색을 blue로 변경
box.className = 'txt-pink'; // 글씨색을 pink로 변경
box.className = 'bg-blue txt-pink'; // 배경색이 blue이면서 글씨색을 pink로 변경

box의 class에 접근하려면 box.className이라는 property를 이용하면 됩니다. 기존에 있던 className을 유지하면서 추가하려면 둘 다 적어줘야 합니다.

실제 프로젝트에서는 class 개수가 상당히 많을 수도 있습니다. 그때마다 어떤 클래스가 있는지 먼저 접근해서 파악하고 추가 제거 수정할 때마다 다시 다 적어줘야 합니다. 그래서 className은 잘 사용하지 않습니다.

box.classList;
DOMTokenList(2) ['box', 'bg-red', value: 'box bg-red']

이럴 때는 classList라는 property를 사용하면 됩니다. classList를 해보면 배열처럼 보이는게 나오고 열어보면 class 두개를 보여줍니다. DOMTokenList 객체는 몇 가지 메소드를 제공하는데요 자주 사용되는 것들을 알아보겠습니다. 

box.classList.add('txt-white');
box.classList.remove('txt-white');

add, remove는 말 그대로 추가 제거를 할 수 있습니다. 

box.classList.add('bg-green','txt-yellow');

여러 개의 class를 추가 제거 하려면 쉼표로 구분해서 적어주면 됩니다.

box.classList.replace('bg-red', 'bg-blue');

추가가 아닌 수정을 할 때는 replace를 이용하는게 편합니다.

setInterval(()=>{
	box.classList.toggle('bg-red');
},1000)

그리고 자주 사용하는 것 중 하나가 특정 class를 넣었다 뺏다 하는 건데 해당 class가 있으면 제거하고 없으면 넣어주는 느낌인데 이럴 때는 toggle을 사용하면 됩니다. setInterval을 이용하면 1초에 한번씩 class가 show되었다가 제거되었다를 반복합니다. 

<div id="box" class="box bg-red">BOX</div>
<ul id="color">
	<li>Red</li>
    <li>Green</li>
    <li>Blue</li>
</ul>
const box = document.getElementById("box");
const color = document.getElementById("color");
color.onclick = function (e) {
 const target = e.target;
 if(target.tagName !== "LI") return;
 target.classList.toggle("txt-pink");
}

className이 color인 ul의 특정 요소를 클릭했을 때 LI가 아니면 return을 시켜주고 LI면 classList에 toggle 메소드를 이용해서 txt-pink라는 클래스를 없으면 넣어주고 있으면 제거하는 기능입니다. 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함