책에 따르면 보통 자바스크립트에서 HTML 태그, class, id를 가져오는 것을 선택 한다고 표현함.
이에 해당되는 함수는
등이 있다.
현재 보고 있는 페이지에서는 docuement.querySelector만 있기 때문에 나머지는 다른 책과 인터넷에서 찾기로 했다.
document.querySelector('선택자')
'HTML태그'
)'.class명'
)'#id명'
)<body>
<div><span id="order">1</span>번째 참가자</div>
<div>제시어: <span id="word"></span></div>
<input type="text">
<button>입력</button>
<button>버튼 2</button>
<button>버튼 3</button>
<script>
const $input = document.querySelector('input');
console.log($input);
</script>
</body>
<div id="foo"></div>
<ul class="list">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
<script>
document.querySelector('#foo')
</script>
document.quertSelector('.item .item:nth-child(2))
형식 : document.querySelectorAll('선택자')
주의 : document.querySelector()
와 달리 선택자를 가진 모든 요소를 가져와 적용시킨다.
예시 1
var
를 씀. <!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>Javascript</title>
</head>
<body>
<p class="abc">Lorem Ipsum Dolor</p>
<p class="abc">Lorem Ipsum Dolor</p>
<p class="abc">Lorem Ipsum Dolor</p>
<script>
var jb = document.querySelectorAll('.abc');
for (var i = 0; i < jb.length; i++) {
jb[i].style.color = 'red';
}
</script>
</body>
</html>
document.getElementById('id명')
<html>
<head>
<title>getElementById 예제</title>
</head>
<body>
<p id="para">어떤 글</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
<script>
function changeColor(newColor) {
var elem = document.getElementById('para');
elem.style.color = newColor;
}
</script>
</html>
getElementById
와 다르게 클래스명과 일치하는 요소 모두 가져온다.<!doctype html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div class="example">
<p>P element in first div with class="example". Div's index is 0.</p>
</div>
<div class="example color">
<p>P element in first div with class="example color". Div's index is 1.</p>
</div>
<div class="example color">
<p>P element in second div with class="example color". Div's index is 1.</p>
<p>Click the button to change the background color of the first div element with the classes "example" and "color".</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note : </strong> The getElementsByClassName() methode is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example color");
x[0].style.backgroundColor = 'red';
}
</script>
</body>
</html>