DOM
은 Document Object Model의 약어이다. 웹 문서의 레이아웃과 컨텐츠를 구성하는 객체 데이터의 표현이다. DOM은 구조화된 nodes
와 property
와 method
를 갖고 있는 object
들로 문서를 표현한다. HTML 내의 접근하여 데이터를 수정할 수 있다.
Document.getElementById()
메서드는 HTML내의 id
속성을 가진 요소에 찾고, Element 객체를 반환한다. id
는 문서 내의 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용하다.
HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <h1 id="mainheading">I ♥ unicorns</h1> <img src="https://devsprouthosting.com/images/unicorn.jpg" id="unicorn" alt="unicorn"> </body> </html>
JS
const heading = document.getElementById('mainheading'); const image = document.getElementById('unicorn');
Document.querySelector
메서드는 HTML내 일치하는 문서의 첫 번째 Element
를 반환한다. 일치하는 요소가 없으면 null
을 반환한다.
CSS 선택자가 HTML 요소에 접근하는 방식과 유사하므로 쓰기에 편리하다.
HTML
<!DOCTYPE html> <html> <head> <title>Todos</title> </head> <body> <h1>Garden Todos</h1> <input type="text" placeholder="New Todo"> <ul> <li>Start Seedlings</li> <li class="done">Deadhead Zinnias</li> <li class="done">Water Tomatoes</li> <li class="done">Harvest Potatoes</li> <li>Prune Roses</li> </ul> <label>Delete All</label> <input type="checkbox" id="scales" name="scales" checked> </body> </html>
JS
const doneTodos = document.querySelectorAll('.done'); const checkbox = document.getElementById('scales');