나의 발자취

[JS] 반복문을 이용해 태그의 색상 일괄 변경 본문

앱 개발/etc

[JS] 반복문을 이용해 태그의 색상 일괄 변경

달모드 2020. 11. 12. 17:25

var alist = document.querySelectorAll('a');

console.log(alist.length);

>> 4

 

이렇게 배열에 a 태그가 총 몇개 있는지 찾는다.

위에서 이어서

var i = 0;

while (i < alist.length){

       console.log(alist[i]);

       i = i+1;

}

하면 a 태그가 모두 출력된다.

이를 응용하여

<!doctype html>
<html>
<head>
    <title>WEBpage front</title>
    <meta charset="utf-8">
    <style>
      

    </style>


</head>



<body>

    <h1><a href="index.html" text-transform:none >WEB</a></h1>
    <input type = "button" value = "night" onclick="
    document.querySelector('body').style.backgroundColor='black';
    document.querySelector('body').style.color='white';">

    <input type = "button" value = "day" onclick="
    document.querySelector('body').style.backgroundColor='white';
    document.querySelector('body').style.color='black';">
 
    
    <input id = "night_day" type = 'button' value="night" onclick="
        var target = document.querySelector('body');
        if (this.value === 'night'){
            target.style.backgroundColor = 'black';
            target.style.color='white';
            this.value = 'day';

            var alist = document.querySelectorAll('a');
            var i = 0;
            while (i < alist.length){
                alist[i].style.color = 'powderblue';
                i = i + 1;
            }
        } else {
            target.style.backgroundColor = 'white';
            target.style.color='black';
            this.value = 'night';

            var alist = document.querySelectorAll('a');
            var i = 0;
            while (i < alist.length){
                alist[i].style.color = 'blue';
                i = i + 1;
            }
        }   


        ">

    <ol>
      <li><a href="1.html" id="text-shadow">HTML</a></li>
      <li><a href="2.html">CSS</a></li>
      <li><a href="3.html">JavaScript</a></li>
    </ol>
    <!--
    <h1><a href="index.html"><font color="red">WEB</font></a></h1>
    <ol>
      <li><a href="1.html"><font color="red">HTML</font></a></li>
      <li><a href="2.html"><font color="red">CSS</font></a></li>
      <li><a href="3.html"><font color="red">JavaScript</font></a></li>
    </ol>
-->


        <p>
            <div>
                <!--
                <img src = "photo.jpeg" width = "600px"  >
                -->
                
                <iframe width="600" height="340" src="https://www.youtube.com/embed/cbuZfY2S2UQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
            </div>
            <h6>link for <a href = "https://opentutorials.org/course/3086" target = "_blank" title="naver website">reference</a></h1>
        
        </p>


</body>
</html>
Comments