IT/js

[javascript] getElementsByClassName 사용시 forEach오류

토희 2022. 5. 17. 20:46
728x90

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 class="blue">제목1</h1>
    <h1 class="blue">제목2</h1>
    <h1 class="blue">제목3</h1>
    <h1 class="blue">제목4</h1>
</body>
</html>
<script>

    var blues = document.getElementsByClassName("blue");
    console.log(blues) 

    //Uncaught TypeError: blues.foreach is not a function
    blues.foreach((ob)=>{
        ob.style.color = "blue";
    })

</script>

 

blue라는 클래스 이름을 가진 값들을 getElementsByClassName로 가져와서 blues로 변수 선언하고,

foreach를 돌리면, 아래와 같은 오류가 발생한다.

blues.foreach is not a function

왜일까?!!!

안되는 이유를 알아보기 위해! console.log(blues)를 찍어본다.

getElementsByClassName 가져온 값은 prototype이 HTMLCollection이다. keypoint!

foreach는 array 배열만 사용 가능하다.

 

 

 

위의 올바르게 수행되게 하기 위해서는 아래와 같이 작성하면 된다!

 

1. blues를 배열로 변경

 

2.getElementsByClassName 대신 querySelectorAll 사용

querySelectorAll(".클래스이름) 으로 가져와야함, 그리고 아래와 같이 forEach

 

 

 

< 아래 전체 코드 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 class="blue">제목1</h1>
    <h1 class="blue">제목2</h1>
    <h1 class="blue">제목3</h1>
    <h1 class="blue">제목4</h1>
</body>
</html>
<script>

    // 1. 배열로 변경
    var blues = document.getElementsByClassName("blue");
    
    Array.from(blues).forEach((i) => {
        i.style.color = "blue";
    });


    // 2. querySelectorAll 사용
    var blues = document.querySelectorAll(".blue"); 

    blues.forEach((ob)=>{
        ob.style.color = "blue";
    })

</script>

1번, 2번을 번갈아 주석 처리 후, 출력해보면 2개 다 오류없이 잘 출력된다.

 

< 출력화면 >

h1 태그들의 color 가 blue로 변경되어 출력됨

 

 

 

 

728x90

'IT > js' 카테고리의 다른 글

URL 파라미터 값 가져오기 (쿼리스트링 값)  (0) 2023.10.23