[JS] HTMLCollection 와 NodeList

kub938·2024년 8월 25일
4

JavaScript

목록 보기
3/4

HTMLCollection 와 NodeList

HTMLCollection

  • HTML DOM는 동적
    • 기본 문서가 변경되면 자동으로 업데이트 된다.
  • 사용법
    • HTMLCollection.length
      • 선택한 collection에 있는 항목의 수를 반환
    • HTMLCollection.item()
      • 주어진 요소를 index 목록으로 반환
    • HTMLCollection.namedItem()
      • 선택한 collection에 특정 이름을 가진 요소를 찾을 때 사용

      • form요소내의 입력필드와 같은 요소를 다룰 때 유용

        //html
        <form id="myForm">
            <input type="text" name="username" value="사용자1">
            <input type="text" name="email" value="user@example.com">
            <input type="submit" value="제출">
        </form>
        //js
        // 폼 요소를 가져옵니다.
        const form = document.getElementById('myForm');
        
        // HTMLCollection을 가져옵니다.
        const inputs = form.elements; // form.elements는 HTMLCollection입니다.
        
        // username 입력 필드를 찾습니다.
        const usernameInput = inputs.namedItem('username');
        console.log(usernameInput.value); // "사용자1"
        
        // email 입력 필드를 찾습니다.
        const emailInput = inputs.namedItem('email');
        console.log(emailInput.value); // "user@example.com"
        
        // 없는 이름을 찾으면 null을 반환합니다.
        const nonExistentInput = inputs.namedItem('nonexistent');
        console.log(nonExistentInput); // null
        

NodeList

  • Array.from으로 Array 변환 가능
  • 유사배열
    • index를 사용해 요소에 접근 할 수 있지만, 배열 메서드(map, forEach,fileter 등) 사용 불가
  • DOM 상태가 변경될 때 자동으로 업데이트
  • 정적/동적을 선택해서 사용할 수 있음

HTMLCollection와 NodeList의 차이점

  • forEach 사용
    • HTMLCollection
      • 배열 메서드 사용 불가
      • for루프나 for of 루프 사용 가능
    • NodeList는 forEach를 사용가능하다.
  • 정적/동적 차이
    • NodeList
      • querySelectorAll()로 생성된 경우 정적 → DOM이 변경되어도 자동으로 업데이트 x
      • childNodes로 생성된 경우 동적 → DOM이 변경될 때 자동으로 업데이트
    • HTMLCollection은 항상 동적임
profile
화면속에서 더 나은 경험을 제공하는 프론트엔드 개발자 김윤배 입니다

1개의 댓글

comment-user-thumbnail
2024년 8월 25일

잘 모르던 개념이었는데 덕분에 잘읽었습니다. 감사합니다.

답글 달기