본문 바로가기
Front-end/Javascript

문서 객체 모델 (DOM)

by warrior.p 2022. 3. 9.

Documet Object Model(DOM)

 

HTML의 '요소' = 자바스크립트의 '문서 객체'

" '문서객체를 조작한다' 말은 HTML 요소들을 조작한다는 의미"

 

  • DOMContentLoaded 이벤트

: 웹 브라우저가 문서 객체(HTML)를 모두 읽고나서 실행하는 이벤트

 

->documet.addEventListner ( 'DOMContentLoaded', ( ) => {      }

 이 코드는 "documet라는 문서객체의 DOMContentLoaded 이벤트가 발생했을 때, 매개변수로 지정한 콜백 함수를 실행하라!

 

 

ex)

<!DOCTYPE html>
  <head>
    <title>Document</title>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const h1 = text => `<h1>${text}</h1>`;
        document.body.innerHTML += h1("head의 script태그 바디에 적용");
      });
    </script>
  </head>
  <body>
  </body>
</html>

  • 문서 객체 가져오기 (HTML 요소 가져오기)

* head, body, title 요소에 접근하는 방법

-> document.head

      document.body

      document.title

 

 

*head, body 내부에 만든 다른 요소들에 접근하는 방법

->documet.querrySelector(선택자) - 1개의 요소만 접근

선택자 대부분 CSS선택자를 입력. 

태그, #id, .class, [속성=값], 선택자_A 선택자_B 

ex)[속성=값] 표현 -> document.querrySelector('img[img src="img/blahblah.png"]

 

->documet.querrySelectorAll(선택자) - 여러 요소에 접근

 문서 객체 여러 개를 배열로 읽어들이는 함수. 내부요소에 접근하려면 반복을 돌려야한다. 

 일반적으로 forEach ()메소드를 사용함.

 

 

( const img = document.querrySelector ('img');

->const 면수를 통해 document에 있는 querrySelector 라는 API를 이용하여 DOM요소를 찾아 변수에 할당하는것!)

 

ex)

<!DOCTYPE html>
  <head>
    <title>Document</title>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const headers = document.querySelectorAll('h1')
        headers.forEach((header)=>{
          header.textContent = 'HEADERS';
          header.style.color='red';
          header.style.backgroundColor='black';
          header.style.padding ='10px';
        })
      });
    </script>
  </head>
  <body>
    <h1></h1>
    <h1></h1>
    <h1></h1>
  </body>
</html>

 

 

심화 ex)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html {
        padding: 0px;
        margin: 0px;
      }

      body {
        background-color: black;
        text-align: center;
      }
      section {
        width: 50%;
        margin: 50px auto;
        background-color: brown;
        border-radius: 20px;
        padding: 20px;
      }
      img {
        z-index: 100;
        will-change: opacity;
      }
      h1,
      h3,
      span {
        color: white;
      }
    </style>
  </head>
  <body>
    <section>
      <img src="img/avatar.png" alt="avatar" />
      <h1 id="brand">Love Love Love</h1>
      <h3>love poem!</h3>
    </section>
    <span>Hello World!</span>
    <script>
      const section = document.querySelector('section');
      const h2 = document.createElement('h2');
      h2.setAttribute('class', 'title'); //<h2 class ="title"><h2> 라는것을 만든 것.
      h2.textContent = 'This is a title'; //<h2 class ="title">This is a title<h2> 라는것을 만든 것.

      // section.appendChild(h2)  append()는 최근에 나옴. appendChind()랑 사용이 흡사함.
      // section 제일 끝에 추가가 됨.
      
      const h3 = document.querySelector('h3');
      section.inserBefore(h2, h3); 
      // h3앞에 h2 삽입.
      
      // section.removeChild(h2);  h2요소 삭제하기 //
      //추후 바뀔일이 없는 변경사항은 innerHTML사용해도 됨 //
    </script>
  </body>
</html>

'Front-end > Javascript' 카테고리의 다른 글

event delegation (이벤트 위임이란)  (0) 2022.03.24
web APIs (Application Programming Interfaces)  (0) 2022.03.11
자주 사용하는 메소드  (0) 2022.03.08
객체  (0) 2022.03.07
함수  (0) 2022.03.07