Dev/JS
getElementsByClassName, querySelectorAll 차이점!
kihyeoksong
2021. 3. 16. 16:45
반응형
우선, 결과만 보자면
querySelectorAll 은 NodeList 객체반환
getElementsByClassName 은 HTMLCollection 객체반환
둘다, 유사배열이다.
예를 들어보자면!
<ul>
<li>가</li>
<li>나</li>
<li>다</li>
<li>라</li>
<li>마</li>
</ul>
위 코드에 querySelector를 사용해 '바'가 담긴 li를 추가해보자!
const ul = document.querySelector('ul');
const li = document.querySelectorAll('li');
let new_item = document.createElement('li');
new_item.textContent = '바';
ul.appendChild(new_item);
console.log(li)
//[li, li, li, li, li]new_item이 NodeList에 포함되지 않음!
위 결과는
querySelectorAll은 변수 new_item이 NodeList에 포함되지 않기 때문에 li를 넣어주지 않는다.
결과값은 기존의 "가,나,다,라,마" 만 보여준다.
getElementsByClassName을 사용한다면?
const li = document.getElementsByClassName('li');
이부분만 바꿔준다면
new_item이 HTMLCollection에 포함되기 때문에 [li, li, li, li, li, li] // 6개 가 되고
결과값은 "가,나,다,라,마,바" 가 된다.
출처: velog.io/@freshnoon/getElementsByClassName-VS-querySelectorAll
getElementsByClassName VS querySelectorAll
querySelectorAll 은 NodeList 객체반환getElementsByClassName 은 HTMLCollection 객체반환둘다, 유사배열이다.querySelectorAll 은 new_item이 NodeList에 포함되지 않기 때문에 li를 넣어주지 않는다
velog.io
반응형