๐Ÿงฉ ์˜ค๋Š˜ ํ•œ ์ผ

์š”์†Œ ์„ ํƒ

๋ชฉ์  ๋ฉ”์„œ๋“œ ์„ค๋ช…
ํŠน์ • ID ์„ ํƒ document.getElementById(id) ๊ฐ€์žฅ ๋น ๋ฅด๊ณ  ๋งŽ์ด ์“ฐ์ž„
ํด๋ž˜์Šค ์„ ํƒ document.getElementsByClassName(class) HTMLCollection ๋ฐ˜ํ™˜
ํƒœ๊ทธ ์„ ํƒ document.getElementsByTagName(tag) HTMLCollection ๋ฐ˜ํ™˜
CSS ์„ ํƒ์ž ์‚ฌ์šฉ document.querySelector(selector) ์ฒซ ๋ฒˆ์งธ ์ผ์น˜ ์š”์†Œ ๋ฐ˜ํ™˜
CSS ์„ ํƒ์ž ๋ชจ๋‘ document.querySelectorAll(selector) NodeList ๋ฐ˜ํ™˜

์š”์†Œ ์ƒ์„ฑ/์ถ”๊ฐ€

๋ฉ”์„œ๋“œ ์„ค๋ช…
document.createElement(tag) ์ƒˆ HTML ์š”์†Œ๋ฅผ ๋งŒ๋“ฆ
document.createTextNode(text) ํ…์ŠคํŠธ ๋…ธ๋“œ ์ƒ์„ฑ
parent.appendChild(child) ์ž์‹ ๋…ธ๋“œ๋ฅผ ๋ถ€๋ชจ์— ์ถ”๊ฐ€
parent.append(...nodes) ์—ฌ๋Ÿฌ ๋…ธ๋“œ๋‚˜ ๋ฌธ์ž์—ด์„ ํ•œ ๋ฒˆ์— ์ถ”๊ฐ€ (์ตœ์‹  ๋ฌธ๋ฒ•)
parent.prepend(...nodes) ๋ถ€๋ชจ์˜ ์ฒซ ๋ฒˆ์งธ ์ž์‹์œผ๋กœ ์ถ”๊ฐ€
element.insertBefore(newNode, referenceNode) ํŠน์ • ์œ„์น˜์— ์‚ฝ์ž…
element.insertAdjacentHTML(position, html) ๋น ๋ฅด๊ฒŒ HTML ์กฐ๊ฐ ์‚ฝ์ž… (beforebegin, afterbegin, beforeend, afterend)

์š”์†Œ ์ˆ˜์ •

๋ฉ”์„œ๋“œ / ์†์„ฑ ์„ค๋ช…
element.textContent ํ…์ŠคํŠธ๋งŒ ๋ณ€๊ฒฝ (HTML ๋ฌด์‹œ)
element.innerHTML ๋‚ด๋ถ€ HTML ์ „์ฒด ๋ณ€๊ฒฝ (์ฃผ์˜: ์„ฑ๋Šฅ ๋А๋ฆผ, XSS ์œ„ํ—˜)
element.outerHTML ์š”์†Œ ์ž์ฒด๋ฅผ HTML ๋ฌธ์ž์—ด๋กœ ๊ต์ฒด
element.setAttribute(name, value) ์†์„ฑ ์ถ”๊ฐ€/์ˆ˜์ •
element.getAttribute(name) ์†์„ฑ๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ
element.removeAttribute(name) ์†์„ฑ ์ œ๊ฑฐ
element.style.property = value ์ธ๋ผ์ธ ์Šคํƒ€์ผ ๋ณ€๊ฒฝ

์ด๋ฒคํŠธ

๋ฉ”์„œ๋“œ ์„ค๋ช…
element.addEventListener(type, handler) ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ๋“ฑ๋ก
element.removeEventListener(type, handler) ๋ฆฌ์Šค๋„ˆ ์ œ๊ฑฐ
element.dispatchEvent(event) ์ด๋ฒคํŠธ ์ˆ˜๋™ ๋ฐœ์ƒ

๐Ÿง  ๋ฐฐ์šด ์  / ์ƒˆ๋กœ ์•Œ๊ฒŒ ๋œ ์ 

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <title>head์— script</title>
    <script>
      const button = document.getElementById('myButton');
      console.log('button:', button); // null
    </script>
  </head>
  <body>
    <button id="myButton">๋ฒ„ํŠผ</button>
  </body>
</html>

๋ธŒ๋ผ์šฐ์ €๋Š” html ๋ฌธ์„œ๋ฅผ ์œ„์—์„œ๋ถ€ํ„ฐ ํ•œ ์ค„์”ฉ ์ฝ์œผ๋ฉฐ ์š”์†Œ๋ฅผ ๋ฐœ๊ฒฌํ•  ๋•Œ๋งˆ๋‹ค DOM ๋…ธ๋“œ๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.

<html> ์„ ๋งŒ๋‚˜๋ฉด document ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๋งŒ๋“ค๊ณ , <head> ๋ฅผ ๋งŒ๋‚˜๋ฉด head ๋…ธ๋“œ๋ฅผ, <body> ๋ฅผ ๋งŒ๋‚˜๋ฉด body ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.

์ด๋•Œ, ๋ธŒ๋ผ์šฐ์ €๊ฐ€ HTML์„ ํŒŒ์‹ฑํ•˜๋‹ค๊ฐ€ <script> ๋ฅผ ๋งŒ๋‚˜๋ฉด ์ž ์‹œ DOM ์ƒ์„ฑ์„ ๋ฉˆ์ถ”๊ณ  JS๋ฅผ ์‹คํ–‰ํ•œ ํ›„, ๋‹ค์‹œ DOM ์ƒ์„ฑ์„ ์ด์–ด๋‚˜๊ฐ„๋‹ค.

์ฆ‰, ๋ธŒ๋ผ์šฐ์ €๊ฐ€ <body>๋ฅผ ๋งŒ๋‚˜๊ธฐ ์ „์—๋„ DOM ์ผ๋ถ€๋Š” ์ด๋ฏธ ์ƒ์„ฑ ์ค‘์ด๋‹ค.

๊ทธ๋Ÿฐ๋ฐ <script>๋ฅผ ๋งŒ๋‚˜๋ฉด ๊ทธ ์‹œ์ ๊นŒ์ง€์˜ DOM๋งŒ ์กด์žฌํ•˜๊ณ , body ์•ˆ์˜ ์š”์†Œ๋“ค์€ ํŒŒ์‹ฑ์ด ์•ˆ ๋œ ์ƒํƒœ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์œ„์˜ ์ฝ”๋“œ๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.