2016년 10월 16일 일요일

예제1

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <style type="text/css">
            .red {
                background-color: red;
            }
            .blue {
                background-color: blue;
            }
            .green {
                background-color: green;
            }
        </style>
    </head>
    <body>
        <div>
            red
        </div>
        <div>
            blue
        </div>
        <div>
            green
        </div>
        <input type="button" value="color" onclick="colorize()" />
        <script type="text/javascript">
            function colorize() {
                <!-- 태그명으로 객체를 받으면 배열형태로 저장이 되고, -->            
                var divs = document.getElementsByTagName('div');
                for(var i = 0; i < divs.length; i++) {
                <!-- 각 div의 class 속성에 innerHTML의 값을 가지게 된다. -->
                    divs[i].setAttribute('class', divs[i].innerHTML)
                }
            }
        </script>
    </body>
</html>
red
blue
green

댓글 없음:

댓글 쓰기