inblog logo
|
jjack1
    JavaScript

    [JS] 4. DOM

    최재원's avatar
    최재원
    Mar 31, 2025
    [JS] 4. DOM
    Contents
    The HTML DOM Tree of Objects1. script의 위치script가 body맨 뒤에 있을 때script가 body 맨 앞에 있을 때2. DOM 제어
    W3Schools.com
    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
    W3Schools.com
    https://www.w3schools.com/js/js_htmldom.asp
    W3Schools.com

    The HTML DOM Tree of Objects

    notion image
    • Document 안에 모든 html 요소가 들어있다
    • Document 로 특정 html 요소를 찾을 수 있다

    1. script의 위치

    script가 body맨 뒤에 있을 때

    <!DOCTYPE html> <html> <body> <h2>My First Page</h2> <p id="demo"></p> <script> let demoDom = document.querySelector("#demo"); demoDom.innerHTML = "Hello World!"; </script> </body> </html>
    notion image

    script가 body 맨 앞에 있을 때


    <!DOCTYPE html> <html> <body> <script> let demoDom = document.querySelector("#demo"); demoDom.innerHTML = "Hello World!"; </script> <h2>My First Page</h2> <p id="demo"></p> </body> </html>
    notion image
    html 코드 라인을 위에서 아래로 한 줄, 한 줄 읽어가는데 script가 실행될 때 demoDom 는 존재하지 않기 때문에 에러가 발생

    2. DOM 제어

    <!DOCTYPE html> <html> <body> <h2>My Second Page</h2> <p class="demo1"></p> <p class="demo1"></p> <p class="demo2"></p> <script> let demo1DomList = document.querySelectorAll(".demo1"); let d1 = demo1DomList[0]; let d2 = demo1DomList[1]; d1.innerHTML = "Hello"; d2.innerHTML = "World"; let demo2Dom = document.querySelector(".demo2"); demo2Dom.innerHTML = "Good"; </script> </body> </html>
    notion image
    • querySelector(), querySelectorAll() 을 사용해 dom 요소를 찾고 내부 html 을 변경 할 수 있다
    • querySelector() → 단일 오브젝트를 찾을
      • notion image
    • querySelectorAll() → 여러 개의 오브젝트를 찾을 때
      • notion image
         
    querySelector() → ()안에 들어가는 문자열은 선택자 문자열이다. CSS에서 사용하는 선택자와 동일하다 querySelector(”#demo”) → <p id="demo"></p> querySelector(”.demo”) → <p class="demo"></p> querySelector(”p”) → <p></p>
     
    Share article
    Contents
    The HTML DOM Tree of Objects1. script의 위치script가 body맨 뒤에 있을 때script가 body 맨 앞에 있을 때2. DOM 제어

    jjack1

    RSS·Powered by Inblog