JavaScript/생활코딩

웹브라우저 자바스크립트 - HTMLCollection

점미 2018. 11. 26. 14:26



HTMLCollection - https://opentutorials.org/course/1375/6666



리턴되는 값이 복수인 경우 HTMLCollection이라는 객체의 element를 담아서 리턴한다.


HTMLCollection의 목록은 실시간으로 변경된다.


<!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'); //lis에 HTMLCollection이 담겨진다. 배열을 사용할 수 있다는 뜻이다.

for(var i = 0; i < lis.length; i++){

    console.log(lis[i]);

}

console.groupEnd();// 여기까지 그룹핑


console.group('after');

lis[1].parentNode.removeChild(lis[1]); //li중에서 두번째 element를 삭제.

for(var i = 0; i < lis.length; i++){

    console.log(lis[i]);

}

console.groupEnd();

</script>

</body>

</html>




[결과화면]