39장 DOM(8.스타일, 9.DOM 표준)
8. 스타일
1. 인라인 스타일 조작
HTMLElement.prototype.style 프로퍼티는 setter와 getter 모두 존재하는 접근자 프로퍼티로서 요소 노드의 인라인 스타일을 취득하거나 추가 또는 변경한다.
<!DOCTYPE html>
<html lang="ko">
<body>
<div style="color: red">Hello World</div>
<script>
$div = document.querySelector("div");
console.log($div.style); // CSSStyleDeclaration { 0: 'color', ... }
// 인라인 스타일 변경 및 추가
$div.style.color = "blue";
$div.style.width = '100px';
</script>
</body>
</html>
CSS 프로퍼티는 케밥 케이스를 따른다. 이에 대응하는 CSSStyleDeclaration 객체의 프로퍼티는 카멜 케이스를 따른다. 예를 들어, CSS 프로퍼티 background-color에 대응하는 CSSStyleDeclaration 객체의 프로퍼티 backgroundColor이다.
$div.style.backgroundColor = 'yellow';
$div.style['background-color'] = 'yellow';
2. 클래스 조작
className
Element.prototype.className 프로퍼티는 setter와 getter 모두 존재하는 접근자 프로퍼티로서 HTML 요소의 class 어트리뷰트 값을 취득하거나 변경한다.
요소 노드의 className 프로퍼티를 참조하면 class 어트리뷰트 값을 문자열로 반환하고, 요소 노드의 className 프로퍼티에 문자열을 할당하면 class 어트리뷰트 값을 할당한 문자열로 변경한다.
<div class='box red'></div>
...
const $box = document.querySelector('.box');
console.log($box.className); // 'box red'
$box.className = $box.className.replace('red','blue');
classList
Element.prototype.classList 프로퍼티는 class 어트리뷰트의 정보를 담은 DOMTokenList 객체를 반환한다.
<div class='box red'></div>
...
const $box = document.querySelector('.box');
console.log($box.classList);
// DOMTokenList(2) [length:2, value: 'box red', 0: 'box', 1: 'red']
// DOMTokenList 객체 메서드
// add : class 추가
$box.classList.add('foo');
$box.classList.add('bar','baz');
// remove : class 제거
// 해당 class 어트리뷰트가 없으면 에러 없이 무시된다.
$box.remove('foo');
// item(index) : index에 해당하는 클래스 반환
$box.classList.item(0);
// contains(className) : 일치하는 클래스가 있는지 확인
$box.classList.contains('box'); // true
// replace(oldClassName, newClassName) : 클래스 변경
$box.classList.replace('red','blue');
// toggle(oldClassName[, force]) : 클래스가 없으면 추가하고, 있으면 제거
$box.classList.toggle('red');
// true : 강제로 추가, false: 강제로 제거
$box.classList.toggle('red',true);
$box.classList.toggle('red',false);
3. 요소에 적용되어 있는 CSS 스타일 참조
style 프로퍼티는 인라인 스타일만 반환한다. 따라서 클래스를 적용한 스타일이나 상속을 통해 암죽적으로 적용된 스타일은 style 프로퍼티로 참조할 수 없다. HTML 요소에 적용되어 있는 모든 CSS 스타일을 참조해야 할 경우 getComputedStyle 메서드를 사용한다.
window.getComputedStyle(element[, pseudo]) 메서드는 첫 번째 인수로 전달한 요소 노드에 적용되어 있는 평가된 스타일을 CSSStyleDeclaration 객체에 담아 반환한다. 평가된 스타일이란 요소 노드에 적용되어 있는 모든 스타일( 링크 스타일, 임베딩 스타일, 인라인 스타일, 자바스크립트에서 적용한 스타일, 상속된 스타일, 기본 스타일 등)이 조합되어 최종적으로 적용된 스타일을 말한다.
getComputedStyle 메서드의 두 번째 인수로 :after, :before와 같은 의사 요소를 지정하는 문자열을 전달할 수 있다.
const computedStyle = window.getComputedStyle($box);
console.log(computedStyled.width); // 최종 적용된 너비
문제
문제1
1. DOMTokenList 객체의 remove 객체를 이용해 class 어트리뷰트를 제거할 때, 해당 어트리뷰트가 없으면 에러가 발생한다.
2. Element.prototype.className 프로퍼티는 DOMTokenList 객체의 add 메서드를 이용해 해당 요소의 클래스를 추가할 수 있다.
3. style 프로퍼티는 요소 노드에 적용되어 있는 모든 스타일 중 인라인 스타일만 반환합니다.
문제2
아래 코드에서 console 출력이 blue로 변경되는 방법을 2개 이상 작성해주세요.
<!DOCTYPE html>
<html lang="ko">
<body>
<div class="red">Hello World</div>
<script>
$div = document.querySelector(".red");
console.log($div.className); // red
</script>
</body>
</html>
답
문제1(X, X, O)
1. 해당 어트리뷰트가 없어도 에러 없이 무시된다.
2. classList에 대한 설명입니다.
문제2
<!DOCTYPE html>
<html lang="ko">
<body>
<div class="red">Hello World</div>
<script>
$div = document.querySelector(".red");
// $div.className = $div.className.replace("red", "blue");
// $div.classList.replace("red", "blue");
// ["red", "blue"].forEach((ele) => $div.classList.toggle(ele));
console.log($div.className);
</script>
</body>
</html>'딥다이브' 카테고리의 다른 글
| [딥다이브] 39장 DOM(6.DOM 조작 ~ 7.어트리뷰트) (2) | 2023.05.29 |
|---|---|
| [딥다이브] 39장 DOM(3.노드 탐색 ~ 5.요소 노드의 텍스트 조작) (0) | 2023.05.24 |
| [딥다이브] 39장 DOM(1.노드~2.요소 노드 취득) (1) | 2023.05.20 |
| [딥다이브] 25장 클래스 (3) | 2023.05.05 |
| [딥다이브] 19장 프로토타입 (0) | 2023.05.01 |