본문 바로가기

JavaScript/Interactive JavaScript

[JavaScript] 스타일 다루기

1. style 프로퍼티 활용하기 : element.style.styleName = 'value';

 

const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');

today.children[0].style.textDecoration = 'line-through';
today.children[0].style.backgroundColor = '#DDDDDD';
today.children[2].style.textDecoration = 'line-through';
today.children[2].style.backgroundColor = '#DDDDDD';

프로퍼티에 styleName을 넣을 때에는 하이픈을 제거하고 대문자로 변경


 

2. class 변경을 통해 간접적으로 스타일 적용하기 : element.className, element.classList

 

const today = document.querySelector('#today');
const tomorrow = document.querySelector('#tomorrow');

// elem.classList: add, remove, toggle
const item = tomorrow.children[1];
item.classList.add('done');
item.classList.remove('done');
item.classList.toggle('done');

// elem.className
today.children[1].className = 'done';
.done {
  opacity: 0.5;
  text-decoration: line-through;
}

 

classList.add('done', 'other') : 'done', 'other' 클래스 추가

classList.remove('done', 'other') : 'done', 'other'  클래스 삭제

classList.toggle('done', 'true' or 'false') : 'done' 클래스  추가 or 제거 

 

2-1. classList 유용한 메소드

 

메소드 내용 참고사항
classList.add 클래스 추가하기 여러 개의 값을 전달하면 여러 클래스 추가 가능
classList.remove 클래스 삭제하기 여러 개의 값을 전달하면 여러 클래스 삭제 가능
classList.toggle 클래스 없으면 추가, 있으면 삭제하기 하나의 값만 적용 가능하고,
두 번째 파라미터로 추가 또는 삭제 기능을 강제할 수 있음