[js] DOM

lilyoh·2020년 7월 25일
0

1. DOM 이란

  • Document Object Model 의 약자.
  • 웹 페이지를 자바스크립트로 제어하기 위한 객체 모델을 의미한다.
  • window 객체의 document 프로퍼티를 통해서 사용할 수 있다.
  • window = 창 / document = 윈도우에 로드된 문서

js 가 html 에 접근하기 위한 수단 dom
html 을 객체로 갖고 있는 모델
트리 구조로 된 객체 모델

2. 제어 대상 찾기

  • 문서로 자바스크립트를 제어하려면 먼저 제어의 대상이 되는 객체를 찾아야 한다.
  • 문서 내에서 객체를 찾을 때는 document 객체의 메소드를 이용한다.

1) document.getElementsByTagName

  • 인자로 전달된 태그명에 해당하는 객체들을 찾아서 그 리스트를 NodeList 라는 유사 배열에 담아서 반환한다. NodeList 는 배열은 아니지만 length 와 배열접근연산자를 사용해서 엘리먼트를 조회할 수 있다.
  • 조회 대상을 좁히고 싶다면? 먼저 부모 태그의 객체를 찾고, 해당 객체를 사용해서 또 객체들을 찾는다. 아래를 참고하자.
<script>
    var ul = document.getElementsByTagName('ul')[0];
    var lis = ul.getElementsByTagName('li');
    for(var i=0; lis.length; i++){
        lis[i].style.color='red';   
    }
</script>

2) document.getElementsByClassName

  • 클래스 속성값을 기준으로 객체를 조회한다.

3) document.getElementById

  • id 값을 기준으로 객체를 조회하며, 성능 면에서 가장 우수하다.
  • id 값은 고유하기 때문에 'elements' 가 아니라 'element' 인 것에 유의하자.

4) document.querySelector

  • css 선택자의 문법을 이용해서 객체를 조회한다.
  • 선택자에 해당하는 첫 번째 요소에 대해 작동한다.

5) document.querySelectorAll

  • css 선택자에 해당하는 모든 객체를 조회한다.

3. HtmlElement

객체 타입 확인

  • getElement* 메서드를 통해 원하는 객체를 조회했다면 이 객체들을 대상으로 구체적인 작업을 처리해야 한다. 이를 위해서는 획득한 객체가 무엇인지 알아야 한다. 그래야 적절한 메소드나 프로퍼티를 사용할 수 있다.
<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="active">JavaScript</li>
</ul>
<script>
    var li = document.getElementById('active');
    console.log(li.constructor.name); // HTMLLIElement
    var lis = document.getElementsByTagName('li');
    console.log(lis.constructor.name); // HTMLCollection
</script>
  • 실행결과가 하나인 경우 HTMLLIElement, 복수인 경우 HTMLCollection 이 리턴된다.

상속

<a id="anchor" href="http://opentutorials.org">opentutorials</a>
<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="list">JavaScript</li>
</ul>
<input type="button" id="button" value="button" />
<script>
    var target = document.getElementById('list');
    console.log(target.constructor.name); // HTMLLIElement
 
    var target = document.getElementById('anchor');
    console.log(target.constructor.name); // HTMLAnchorElement
 
    var target = document.getElementById('button');
    console.log(target.constructor.name); // HTMLInputElement
 
</script>
  • 엘리먼트에 따라 프로퍼티가 다르다. 하지만 모든 엘리먼트들은 HTMLElement 를 상속받고 있다.
// HTMLLIElement
interface HTMLLIElement : HTMLElement {
           attribute DOMString       type;
           attribute long            value;
};

// HTMLAnchorElement
interface HTMLAnchorElement : HTMLElement {
           attribute DOMString       accessKey;
           attribute DOMString       charset;
           attribute DOMString       coords;
           attribute DOMString       href;
           attribute DOMString       hreflang;
           attribute DOMString       name;
           attribute DOMString       rel;
           attribute DOMString       rev;
           attribute DOMString       shape;
           attribute long            tabIndex;
           attribute DOMString       target;
           attribute DOMString       type;
  void               blur();
  void               focus();
};

Dom Tree

  • 모든 엘리먼트는 HTMLElement 의 자식이다. 따라서 HTMLElement 프로퍼티를 똑같이 가지고 있다. 동시에 엘리먼트의 성격에 따라서 자신만의 프로퍼티를 가지고 있다. HTMLElement 는 Element 의 자식이고 Element 는 Node 의 자식이다. Node 는 Object 의 자식이다. 이러한 관계를 Dom Tree 라고 한다.
  • 돔 트리를 이해해야 웹 브라우저를 자바스크립트로 제어할 수 있다. 필요한 API 를 찾아내는 것도 쉬워진다.

4. HTMLCollection

  • 리턴 결과가 복수인 경우에 사용하게 되는 객체이다.
  • 유사배열로 배열과 비슷한 사용방법을 가지고 있지만 배열은 아니다.
  • HTMLCollection 의 목록은 실시간으로 변경된다.
  • 아래 코드를 보면 lis 변수의 인덱스 1 요소를 지웠고, 변경사항이 실시간으로 적용된 것을 after 아래의 결과값에서 확인할 수 있다.
<!DOCTYPE html>
<html>
<body>
<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="active">JavaScript</li>
</ul>
<script>
console.group('before');
var lis = document.getElementsByTagName('li');
for(var i = 0; i < lis.length; i++){
    console.log(lis[i]);
}
console.groupEnd();
console.group('after');
lis[1].parentNode.removeChild(lis[1]);
for(var i = 0; i < lis.length; i++){
    console.log(lis[i]);
}
console.groupEnd();
</script>
</body>
</html>

5. Document 객체

  • document 객체는 dom 의 시작점이고 문서 전체를 의미하는 node 이기도 하다.

  • document 는 dom 에서 정의되어 있는 규격 또는 인터페이스

  • html 문서에서 document 가 실제 사용되는 것은 아니고 HTMLDocument 라고 하는 구체적인 객체가 정의되어서 HTMLDocument 라는 객체를 사용하는 것

  • HTMLDocument 객체는 html 전체를 대표하는 객체이면서 전체를 대표하는 node 라고 할 수 있다.

  • document 객체가 주로 하는 것은 새로운 노드를 생성하는 것이다.
    : createElement()
    : createTextNode()

  • 문서 정보 api 를 불러온다.
    : title
    : URL
    : referrer
    : lastModified

참고: 생활코딩

Replit Review

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1 id="h1-title">
      안녕하세요
    </h1>
    
    <script>
      let pTag = document.createElement('p'); // p 태그 생성
      pTag.className = 'dom'; // p 태그의 클래스 네임을 'dom' 으로 추가
      pTag.innerHTML = "DOM"; // p 태그 내에 "DOM" 텍스트 생성
      document.getElementById('h1-title').appendChild(pTag); // h1 태그 내에 p 태그 삽입
      // p 태그 삽입할 때 h1 태그가 아닌 h1 태그에 붙여진 id 값을 찾아서 삽입해줘야 한다
    </script>  
  </body>
</html>

0개의 댓글