HTMLCollection

HTMLCollection은 리턴 결과가 복수인 경우에 사용하게 되는 객체다. 유사배열로 배열과 비슷한 사용방법을 가지고 있지만 배열은 아니다.

HTMLCollection

  • 유사배열로 배열과 비슷한 사용방법을 가지고 있지만 배열은 아님

  • HTMLCollection 객체는 실시간으로 변경(한번 탐색한 HTMLCollection의 내부 Element들을 제거하거나 추가한 후 다시 탐색할 필요가 없음)

<!DOCTYPE html>
<html>
<body>
<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li id="active">JavaScript</li>
</ul>
<script>
    console.group('before');
    // lis 변수에 li요소들을 
    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>

Last updated

Was this helpful?