[TypeScript에서 DOM 다루기] - HTMLElement와HTMLCollection

조민호·2023년 10월 27일
0

DOM객체를 불러올 때 보통 아래의 메소드들을 주로 사용하곤 합니다

  • getElementsByTagName()
  • getElementById()
  • getElementsByClassName()
  • querySelector()
  • querySelectorAll()

그렇지만 위의 모든 메소드가 같은 리턴타입을 가지진 않습니다

정확히 말하면, 리턴하는 것은 각 요소에 따른 DOM객체가 맞으나

단수 , 복수 의 형태로 다른 것입니다

  • getElementById() , querySelector() 의 리턴 데이터 타입은 HTMLLIElement
  • getElementsByTagName() 의 리턴 데이터 타입은 HTMLCollection

즉, 실행결과가 하나인 경우는 HTMLLIElement , 복수인 경우는 HTMLCollection 을 리턴하게 됩니다

대표적인 예시입니다

<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="active">JavaScript</li>
</ul>

let li = document.getElementById('active');
console.log(li.constructor.name);      // HTMLLIElement 
let lis = document.getElementsByTagName('li');
console.log(lis.constructor.name);    // HTMLCollection

HTMLLIELement의 경우, 리턴되는 DOM객체가 하나라고 해서 무조건 HTMLLIELement만 리턴되는 것은 아닙니다

엘리먼트의 종류에 따라서 리턴되는 객체가 조금씩 다릅니다

<a id="anchor" href="http://naver.com">네이버</a>
<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="list">JavaScript</li>
</ul>
<input type="button" id="button" value="button" />

let target = document.getElementById('list');
console.log(target.constructor.name); **// HTMLLIElement**
 
let target = document.getElementById('anchor');
console.log(target.constructor.name); **// HTMLAnchorElement**
 
let target = document.getElementById('button');
console.log(target.constructor.name);  **// HTMLInputElement**

**DOM 객체의 HTML요소타입 은 .constructor.name으로 조회가 가능합니다**


HTMLCollection의 경우, 유사배열 형태로 리턴이 되기 때문에

배열의 일부 메소드들을 사용할 수 있으며 인덱스로 접근이 가능합니다

  • HTMLCollection.item()
  • HTMLCollection[ ]
<ul>
	<li>1번째 li</li>
	<li>2번째 li</li>
</ul>

let c = document.getElementsByClassName('i');

let first = c.item(0); // 1번째 li

let second = c[1]; //2번째 li
  • HTMLCollection.nameItem(id값)
  • HTMLCollection[id값]
<ul>
	<li id="first">1번째 li</li>
	<li>2번째 li</li>
</ul>

let c = document.getElementsByClassName('i');

let first1 = c.nameitem('first');

let first2 = c['first'];
profile
웰시코기발바닥

0개의 댓글