본문 바로가기

JS

JS DOM/스타일/이벤트 정리

DOM / 스타일

 

 

1. node 가져오기

let node = document.querySelector('.first');
console.log(node);

 

 

 

2. class에 접근하기 

2-1) 클래스 이름 추출

let node = document.querySelector('.first');
console.log(node.className);

 

2-2) 클래스 리스트 추출 (클래스가 여러개인 경우 배열로 추출)

let node = document.querySelector('.first');
console.log(node.classList);

 

  • classList.add : 클래스 추가
  • classList.remove : 클래스 삭
  • classList.contains : 존재여부를 확인 (T/F 반환)

 

 

3-1. 표준 속성 가져오기

let node = document.querySelector('.first');
console.log(node.id);

 

3-2. 비표준 속성 가져오기

비표준 속성에 접근하기 위해서는 위와 같은 방법을 이용하여 접근할 수 있다. 

 

[getter]

let node = document.querySelector('.first');
console.log(node.getAttribute('hello')); //hello라는 비표준 속성이 태그 안에 존재하는 것!

ㄴhello attribute의 value값인  world 출력 

 

[setter]

let node = document.querySelector('.first');
node.setAttribute('hello', 'universe') //hello라는 비표준 속성의 값인 world가 universe로 변경됨
console.log(node.getAttribute('hello')); //hello라는 비표준 속성이 태그 안에 존재하는 것!

ㄴ hello attribute의 value값인 world를 universe로 변경

 

+ attribute 의 값들을 열거할 수 있는 방법 attributes

let node = document.querySelector('.first');
console.log(node.attributes);

 

 

 

6-1. HTML 의 텍스트 수정하기!

insertadjacentHTML을 이용한다. 

insertadjcentHTML의 옵션값

let node = document.querySelector('.first');
node.insertAdjacentHTML('beforebegin', '<p>first</p>');
node.insertAdjacentHTML('afterbegin', '<p>second</p>');
node.insertAdjacentHTML('beforeend', '<p>third</p>');
node.insertAdjacentHTML('afterend', '<p>fourth</p>');

 

 

6-2. Node 객체를 HTML에 붙일 때는 'appendChild' 메서드 이용

    //랜더링하는 함수
    function renderItem(){
      itemList.forEach((item)=> {
        const newItem = getTodoItemElem(item);
        todolist.appendChild(newItem); //노드를 붙일 때는 appendChild
        })
    }

 

 

 

7. 스타일 변경하기

 

7-1)

let node = document.querySelector('.first');
node.style.cssText = `background-color: red`;

ㄴ but, 위의 방법은 기존 스타일이 삭제되는 위험이 있으므로, 지양!! (배경화면 뿐만 아니라 style태그에 모든 값이 리셋)

 

7-2) 

let node = document.querySelector('.first');
node.style.backgroundColor = 'pink';

ㄴ node의 style태그의 backgroundColor 속성에 접근하여 처리할 수 있다. 

ㄴ 하이픈 된 속성은 카멜케이스로 접근 가능

ㄴ but, 해당 방법은 style 태그에 기재된 속성에만 접근 가능하다. 

 

7-3) 계산된 스타일에 접근하기 (css 파일에 기재된 스타일에 접근)

let node = document.querySelector('.first');
console.log(getComputedStyle(node)['background-color']);

ㄴ css파일에 정의된 스타일에 접근하여 값을 가져온다. 

 

 

 


 

 

이벤트

 

  • 이벤트 핸들러 프로퍼티 방식은 하나의 이벤트 핸들러만을 바인딩할 수 있다. (node.oclick = function()) 
addEventListener
const button = document.querySelector(button);

function handleButton(){
 ...
}

button.addEventListener('click', handleButton);

ㄴ이벤트 핸들러를 인수로 전달하여 바인딩한다.

ㄴ 하나 이상의 이벤트 핸들러가 모두 호출된다. 

 

만약, 이벤트핸들러 + addEventListener 모두 이벤트를 등록하게 된다면, 서로 영향을 주지 않는다. 

 

 

 

 

 

버블링 & 캡쳐링

버블링 : 자식 > 부모요소로 이벤트 핸들러가 작동하는 것

캡쳐링 : window > 자식 요소로 이벤트 핸들러가 작동하는 것 

 

 

이벤트위임

여러개의 하위 DOM 요소에 이벤트 핸들러를 등록하는 대신, 하나의 상위요소에 등록하여 하위 요소들을 캐치함으로써 사용할 수 있다.