문서 객체 가져오기
document.head , document.body , document.title 등을 이용
head와 body 요소 내부에 만든 다른 요소들은 다음과 같은 별도의 메소드를 사용해서 접근
document.querySelector(선택자) : 요소를 하나만 추출
document.querySelectorAll(선택자) : 선택자에 해당하는 모든 문서 객체를 배열로 가져옴
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/*
*/
document.addEventListener('DOMContentLoaded', () => {
// 요소를 읽어들임. 제일 먼저 나오는 요소 하나만 가져옴 h1
const header = document.querySelector('h1');
// 텍스트와 스타일을 변경
header.textContent = 'HEADERS';
header.style.color = 'white';
header.style.backgroundColor = 'black';
header.style.padding = '10px';
// querySelectorAll 는 배열로 들고오기 때문에 반복문을 돌려야 함
// 요소를 읽어들임 h2 전체를 배열로 들고옴
const headersAll = document.querySelectorAll('h2');
// 텍스트와 스타일을변경
// 일반적으로 forEach() 메소드를 사용해서 반복을 돌림
headersAll.forEach((item) => {
item.textContent = 'headersAll';
item.style.color = 'red';
item.style.backgroundColor = 'black';
item.style.padding = '20px';
});
// for문을 이용하여 반복문 돌리기
// for (let idx in headersAll) {
// headersAll[idx].style.color = 'blue';
// }
for (let i = 0; i < headersAll.length; i++) {
headersAll[i].style.color = 'blue';
}
// h1 전체 color 를 red로 변경
const h1All = document.querySelectorAll('h1');
h1All.forEach((item) => {
item.style.color = 'red';
})
});
</script>
</head>
<body>
<h1></h1>
<h1>2</h1>
<h2></h2>
<h2></h2>
<h2></h2>
<h2></h2>
</body>
</html>