브라우저가 자동으로 만들어 놓은 객체를 찾는 다양한 방법
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>
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 선택자 문법인 태그, 클래스 지정, 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>
예시
<!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>