TIL | JS DOM

cos·2022년 2월 13일
0
post-thumbnail

DOM?

DOM은 Document Object Model의 약어이다. 웹 문서의 레이아웃과 컨텐츠를 구성하는 객체 데이터의 표현이다. DOM은 구조화된 nodespropertymethod를 갖고 있는 object들로 문서를 표현한다. HTML 내의 접근하여 데이터를 수정할 수 있다.

getElementById

Document.getElementById() 메서드는 HTML내의 id 속성을 가진 요소에 찾고, Element 객체를 반환한다. id는 문서 내의 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용하다.

ex)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <h1 id="mainheading">I &hearts; 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');

querySelector

Document.querySelector 메서드는 HTML내 일치하는 문서의 첫 번째 Element를 반환한다. 일치하는 요소가 없으면 null을 반환한다.
CSS 선택자가 HTML 요소에 접근하는 방식과 유사하므로 쓰기에 편리하다.

ex)

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');
profile
The journey is the reward

0개의 댓글