WEB JavaScript DOM

Develop My Life·2020년 5월 28일
0

WEB JavaScript

목록 보기
4/9

제어 대상 찾기

브라우저가 자동으로 만들어 놓은 객체를 찾는 다양한 방법

태그 이름으로 찾기

document.getElementsByTagName 활용하여 유사배열 찾기

예시

<!DOCTYPE html>
<html>
<body>
<ul>
    <li>토마토</li>
    <li>사과</li>
    <li>딸기</li>
</ul>
<script>
    var red_fruit = document.getElementsByTagName('li');
    for(var i=0; i < red_fruit.length; i++){
        red_fruit[i].style.color='red';   
    }
</script>
</body>
</html>

클래스 이름으로 찾기

document.getElementsByClassName('red') 활용하여 유사 배열 찾기

예시

<!DOCTYPE html>
<html>
<body>
<ul>
    <li class = "yellow">바나나</li>
    <li class = "red">사과</li>
    <li class = "red">딸기</li>
</ul>
<script>
    var red_fruit = document.getElementsByClassName('red');
    for(var i=0; i < red_fruit.length; i++){
        red_fruit[i].style.color='red';   
    }
</script>
</body>
</html>

ID로 찾기

document.getElementByID('yellow') 활용하여 하나의 Element 찾기

예시

<!DOCTYPE html>
<html>
<body>
<ul>
    <li id = "yellow">바나나</li>
    <li class = "red">사과</li>
    <li class = "red">딸기</li>
</ul>
<script>
    var red_fruit = document.getElementsByClassName('red');
    for(var i=0; i < red_fruit.length; i++){
        red_fruit[i].style.color='red';   
    }
    var yellow = document.getElementById('yellow');
    yellow.style.color = 'yellow';
</script>
</body>
</html>

CSS 선택자 문법 활용하여 찾기

CSS 선택자 문법인 태그, 클래스 지정, ID 지정을 사용

  • document.querySelector('li') - 하나의 Element만 선택

예시

<!DOCTYPE html>
<html>
<body>
    <ol>
        <li>사과</li>
        <li>딸기</li>
        <li id = 'tomato'>토마토</li>
    </ol>
    
    <ul>
        <li class = 'yellow'>바나나</li>
        <li class = 'yellow'>망고</li>
        <li class = 'yellow'>참외</li>
    </ul>
    <script>
        var li = document.querySelector('li');
        li.style.color = 'red';
    </script>
</body>
</html>
  • document.querySelectorAll('li') - 모든 Element 선택

예시

<!DOCTYPE html>
<html>
<body>
    <ol>
        <li>사과</li>
        <li>딸기</li>
        <li id = 'tomato'>토마토</li>
    </ol>
    
    <ul>
        <li class = 'yellow'>바나나</li>
        <li class = 'yellow'>망고</li>
        <li class = 'yellow'>참외</li>
    </ul>
    <script>
        var li = document.querySelectorAll('li');
        for(var i=0;i<li.length;i++){
            li[i].style.color = 'red';
        }
    </script>
</body>
</html>
  • 클래스와 id 값으로 선택

예시

<!DOCTYPE html>
<html>
<body>
    <ol>
        <li>사과</li>
        <li>딸기</li>
        <li id = 'tomato'>토마토</li>
    </ol>
    
    <ul>
        <li class = 'yellow'>바나나</li>
        <li class = 'yellow'>망고</li>
        <li class = 'yellow'>참외</li>
    </ul>
    <script>
        var tomato = document.querySelector('#tomato');
        tomato.style.color = 'red';
        
        var yellow = document.querySelectorAll('.yellow');
        for(var i=0;i<yellow.length;i++){
            yellow[i].style.color = 'yellow';
        }
    </script>
</body>
</html>

0개의 댓글