document.querySelectorAll 에서는 addEventListener가 왜 안될까요?

안녕하세요? addEventListener를 추가 할려고 하는데
//var selectall = document.getElementById(‘student1’); 로 하면 잘 되는데
var selectall = document.querySelectorAll(‘select’); 로 하면 오류가 나네요.

오류 메시지는 temp.html:30 Uncaught TypeError: selectall.addEventListener is not a function
at temp.html:30
(anonymous) @ temp.html:30
왜그럴까요? ㅜㅜ

아래는 전체 코드 입니다.

    <title>title</title>

    <link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<select name="student1" id="student1" onfocus="console.log(this.options[this.options.selectedIndex].text)">

        <option value="">직업선택</option>

        <option value="학생">학생</option>

        <option value="회사원">회사원</option>

        <option value="기타">기타</option>

</select>



    <select name="student2" id="student2" onfocus="console.log(this.options[this.options.selectedIndex].text)">

            <option value="">직업선택2</option>

            <option value="학생">학생2</option>

            <option value="회사원">회사원2</option>

            <option value="기타">기타2</option>

    </select>

    <script type="text/javascript">

        var selectall = document.querySelectorAll('select'); 

        //var selectall = document.getElementById('student1');

        

        selectall.addEventListener('focus', function(event){

      console.log ('Hello world, '+ event.target.value);

      console.log(event.target.options.selectedIndex)

});

    [temp.zip|attachment](upload://1iVJN73kI8ovBMcBcmiDbXbnVnY.zip) (629 바이트) 

</script>

document.getElementById는 단일 DOM 객체를 가져오지만, document.querySelectorAll은 NodeCollection을 가져오기 때문입니다.
또한 NodeCollection은 숫자 인덱스를 가지고 있고 length property를 가지고 있지만, 배열은 아니므로 forEach등의 Iterator Function을 호출할 수 없습니다.

아래와 같이 해 보세요.

for(var i = 0; i<selectall.length; i++) {
selectall[i].addEventListener(…);
}

2개의 좋아요