DOM

김래영·2019년 11월 12일
0

Javascript

목록 보기
2/21

Document Object Model


HTML 은 구성을 짜는 설계도 같은 역할을 하고, CSS 로 디자인을 했다면, DOM을 이용해서 화면을 만들어 준다.

document


html 문서의 구조와 관계를 객체로 표현한 모델.
html 문서도 javascript 객체도 부모와 자식이 있는 트리구조 이다.
document라는 전역 변수로 접근이 가능하다.

아래 그림과 같이 documenthtml이 담겨있다.

$0 키워드를 이용해서 콘솔에서 선택한 엘리먼트에 접근할 수 있다


console.dir로 접근하면 객체 모양으로 element가 가지고 있는 다양한 속성들을 볼 수 있다


DOM 엘리먼트를 선택하는 방법


querySelector

class 선택: .
document.querySelector('.show-element');

Id 선택: #

  • 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환한다.
  • 일치하는 요소가 없으면 null을 반환한다.
  • 클래스를 사용하는 classList 중 가장 첫번째 요소를 가지고 온다.

querySelectorAll

document.querySelectorAll('.customize-dialog');

  • nodeList 유사배열로 반환된다.
  • 일치하는 것이 없는 경우에는 비어 있는 NodeList 빈배열을 반환한다.

getElementsByClassName

document.getElementsByClassName('storylink');

  • HTMLCollection 유사배열로 반환된다.
  • 일치하는 것이 없는 경우에는 비어 있는 HTMLCollection 빈배열을 반환한다.

getElementById

document.querySelector('#one-google');

  • ID는 대소문자를 구분하는 문자열로, 문서 내에서 유일해야 한다.
  • 하나의 값은 하나의 요소만 사용할 수 있다.
  • 일치하는 요소가 없으면 null을 반환한다.

getElementsByTagName

document.getElementsByTagName('span');

  • HTMLCollection 유사배열로 반환된다.
  • 일치하는 것이 없는 경우에는 비어 있는 HTMLCollection 빈배열을 반환한다.

부모, 형제, 자식 요소들을 선택하는 방법


parentElement

elemnt.parentElement;

  • 현재 element 의 부모 element 를 반환한다.
  • 요소가 없다면 null.

nextElementSibling

element.nextElementSibling;

  • 현재 element 의 다음 형제 element 를 반환한다.
  • 요소가 없다면 null.

previousElementSibling

element.previousElementSibling;

  • 현재 element 의 이전 형제 element 를 반환한다.
  • 요소가 없다면 null.

children

element.children;

  • 현재 element의 자식 elements를 HTMLCollection 유사배열로 반환한다.

DOM 엘리먼트를 수정하는 작업


1. add, remove, toggle class

add

element.classList.add('hello-world');

  • class를 만들고 추가할 수 있다.

remove

element.classList.remove('hello-world');

  • class를 삭제할 수 있다.

toggle

element.classList.toggle('hello-world');

  • class가 없다면 추가하고 class가 있다면 삭제할 수 있다.

2. Create a DOM element

createElement

document.createElement('a');

  • 'a'태그를 가진 element를 생성한다.

3. Add attributes

setAttribute

element.setAttribute('href', 'https://www.naver.com');

  • 속성을 추가할 수 있다.

4. Append an element

appendChild

element.appendChild(element2);

  • element2를 element의 마지막 자식으로 넣어준다.

prepend

element.prepend(menu);

  • element의 첫번째 자식으로 넣어준다.

4. Removing an element

remove

element.remove()

  • element를 삭제할 수 있다.

DOM 엘리먼트에 대한 이벤트 등록 방법


Events

https://developer.mozilla.org/ko/docs/Web/Events

AddEventListener

element.addEventListener('mouseover', function(){
   console.log('hello world');
});
  • 인자를 최대 3개까지 넣을 수 있다.
  • 첫 번째 인자로는 이벤트 이름을 적고, 두 번째 인자로는 함수를 넣어준다.

Event.target vs Event.currentTarget


target

tbody.addEventListener('click', function(ev){ console.log(ev.target); });

  • target 속성은 해당 이벤트가 발생한 근원지에 위치한 element 요소를 말한다.

currentTarget

tbody.addEventListener('click', function(ev){ console.log(ev.currentTarget); });

  • currentTarget 속성은 실제로 등록된 dom element 정보를 담고있다.
profile
개발 노트

0개의 댓글