seoyoung.dev

[javascript]-DOM Tree/HTMLElement와HTMLCollection 본문

WEB/Javascript

[javascript]-DOM Tree/HTMLElement와HTMLCollection

seo-0 2019. 10. 21. 15:31
자바스크립트 시리즈는 '생활코딩-클라이언트 과목의 '웹브라우저 자바스크립트' 강의'를 참고로
공부하고 기록하기 위한 용도입니다. 

 

-> DOM (document object model) 은 웹페이지를 자바스크립트로 제어하기 위한 객체모델을 의미한다.

window 객체의 document 프로퍼티를 통해 사용할 수 있으며, 앞서 익힌 window 객체가 '창'을 의미한다면, document 객체는 윈도우에 로드된 '문서'를 의미한다. 

 

-> 문서를 자바스크립트로 제어하려면,  제어의 대상에 해당되는 객체를 제일 먼저 찾아야 한다. 

 

* getElementsByTagName()
   <ul>
      <li> html</li>
      <li>css</li>
      <li>JAVASCRIPT</li>
    </ul>
    <ol>
      <li> html</li>
      <li>css</li>
      <li>JAVASCRIPT</li>
    </ol>
  <script>
    var ul = document.getElementsByTagName('ul')[0];
    var lis = ul.getElementsByTagName('li');
    //li 태그를 가진 요소들을 담은 유사 배열
    //ul 태그 하위의 li 태그들만 조회
    for(var i=0;i<lis.length;i++){
      lis[i].style.color ='red';
    }
    </script>

ul의 li 들을 lis 에 저장, color 적용된다. 

* getElementsByClassName() 과 getElementById()
    <ul>
      <li>HTML</li>
      <li class="active">CSS</li>
      <li class="active">JAVASCRIPT</li>
      <li id="act"> getById</li>
    </ul>
  <script>
       var lis = document.getElementsByClassName('active');
       //유사 배열 lis (getElments 이니까 )
       for(var i=0;i<lis.length;i++){
         lis[i].style.color='red';
       }

       var li=document.getElementById('act'); 
       //문서에서 id는 특정한 element하나만을 식별하는 식별자이므로 조회결과는 반드시 한 개 
       li.style.color="blue";
    </script>

class로는 여러요소들 접근 가능, id 는 유일무이 

* querySelector() 과 querySelectorAll()
    <ul>
        <li> html</li>
        <li>css</li>
        <li>JAVASCRIPT</li>
    </ul>
    <ol>
        <li>HTML</li>
        <li class="active">CSS</li>
        <li>JavaScript</li>
    </ol>
      var li=document.querySelector('li');
        //하나의 엘리먼트만 -> 맨처음
      li.style.color='red';

      var li = document.querySelector(".active");
      li.style.color='blue';

      var lis = document.querySelectorAll('li');
         for(var name in lis){
            lis[name].style.color='purple';
         }

querySelectorAll 로 li 엘리먼트 모두 


* HTMLLIElement 와 HTMLCollection
      <ul>
          <li id='active'> html</li>
          <li>css</li>
          <li>JAVASCRIPT</li>
      </ul>
      
    <script>
      var li = document.getElementById('active');
      console.log(li.constructor.name);
      var lis = document.getElementsByTagName('li');
      console.log(lis.constructor.name);
    </script>

[ 실행 결과 ]

HTMLLIElement //단수일 때, return 하는 객체 //li 엘리먼트를 조회해서 LIElement가 리턴 
HTMLCollection //복수일 때, return 하는 객체 //유사배열 - 배열처럼 사용 

- document.getElementById 의 리턴 데이터 타입은 HTMLLIElement

- document.getElementsByTagName 의 리턴 데이터 타입은 HTMLCollection

즉, 실행결과가 하나인 경우는 HTMLLIElement , 복수인 경우는 HTMLCollection 을리턴하고있다.

 

  <a id="anchor" href="http://www.naver.com">naver</a>
      <ul>
          <li id='active'> html</li>
          <li>css</li>
          <li>JAVASCRIPT</li>
      </ul>
      <input type="button" value="button" id="button" />
      
      
    <script>
      var target = document.getElementById('active');
      console.log(target.constructor.name);
      var target = document.getElementById('anchor');
        console.log(target.constructor.name);
      var target = document.getElementById('button');
        console.log(target.constructor.name);
    </script>

[ 실행 결과 ]

HTMLLIElement
HTMLAnchorElement
HTMLInputElement

-> 각 태그마다 html의 element의 속성을 가지면서, 조금씩 다른 속성을 갖고있게된다. 

 

***

- 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();
};

-> element 객체에 따라서 property 가 다르다. 하지만 모든 element 들은 HTMLElement를 상속받는다. 


* DOM Tree

DOM Tree

: 모든 엘리먼트는 HTMLElement 의 자식이다. 

따라서, HTMLElement의 property 를 똑같이 갖고 있게 된다. 동시에 자신만의 property 를 가지고 있다. 

또한, 부모인 Element 는 Node 의 자식이다. Node는 Object의 자식이다.

[출처]

 

The Document Object Model

The Document Object Model So far, we’ve been talking a lot about language and theory. You might be thinking, “When do we get to write a web application?” That’s what the next two chapters are for. In order to write an application, our code needs to be able

web.stanford.edu


* HTMLCollection
    <ul>
        <li> html</li>
        <li>css</li>
        <li>JAVASCRIPT</li>
    </ul>
<script>
      console.group('before');
        var lis = document.getElementsByTagName('li');
        //lis는 HTMLCollection 객체 리턴받는다 ( 복수 )
        //HTMLCollection로 리턴받으므로 유사배열이므로 배열처럼 사용 가능 
        for(var i=0;i<lis.length;i++){
          console.log(lis[i]);
        }
      console.groupEnd();

      console.group('after');
        lis[1].parentNode.removeChild(lis[1]);
        //바로 html 에 적용이 된다. 
        for(var i=0;i<lis.length;i++){
          console.log(lis[i]);
        }
      console.groupEnd();
  </script>