| ๋ชฉ์ | ๋ฉ์๋ | ์ค๋ช |
|---|---|---|
| ํน์ 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 ์์ ์์๋ค์ ํ์ฑ์ด ์ ๋ ์ํ์ด๋ค. ๋ฐ๋ผ์ ์์ ์ฝ๋๋ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.