07-2 자바스크립트 문서 객체 가져오기

onezeun·2022년 2월 2일
0

document.querySelector()

입력한 선택자와 일치하는 문서 내의 첫 번째 element를 반환한다.
일치하는 요소가 없다면 null을 반환한다.

document.querySelector(선택자)
선택자 부분에는 CSS선택자를 입력

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>document.querySelector</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // 태그 선택자
      const h1 = document.querySelector('h1').style.color = 'red'
      // 아이디 선택자 #아이디
      document.D('#header').style.backgroundColor = 'orange'
      // 클래스 선택자 .클래스
      document.querySelector('.center.head').style.textAlign = 'center'
      // 속성 선택자 [속성=값]
      document.querySelector('[type=text').style.borderRadius = '10px'
      // 후손 선택자 선택자_A 선택자_B
      document.querySelector('body input').style.backgroundColor = 'blue'
    })
  </script>
</head>
<body>
  <h1 id='header' class='center head'>안녕하세요</h1>
  <input type="text">
  <input>
</body>
</html>

document.querySelectorAll()

querySelector()가 한 개의 요소를 반환했다면, querySelectorAll()은 주어진 CSS 선택자와 일치하는 모든 요소를 반환한다.

forOf와 같이 씀
왜? 문서 객체 여러 개를 배열로 읽어들이는 함수로 내부의 요소에 접근하고 활용하려면 반복을 돌려야 함

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>document.querySelectorAll</title>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      for (const element of document.querySelectorAll('input')) {
        element.style.backgroundColor = 'red'
      }
    })
  </script>
</head>
<body>
  <h1>안녕하세요</h1>
  <input>
  <input>
</body>
</html>

참고 https://gingerkang.tistory.com/49

profile
엉망진창

0개의 댓글