DOM#
HTML/XML ๋ฌธ์๋ ๋ธ๋ผ์ฐ์ ์์์ DOM ํธ๋ฆฌ๋ก ํํ๋๋ค ๋ฌธ์๊ฐ์ฒด๋ชจ๋ธ(DOM)์ ๋ฐ๋ฅด๋ฉด ๋ชจ๋ HTML tag๋ ๊ฐ์ฒด์ด๋ค.
๋ฌธ์๋ค๋ ์ญ์ ๊ฐ์ฒด๋ค. ์ด๋ฐ ๋ชจ๋ ๊ฐ์ฒด๋ ์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ํตํด์ ์ ๊ทผํ ์ ์๊ณ , ํ์ด์ง๋ฅผ ์กฐ์ํ ๋ ์ด ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ค.
html
์ ๋ฃจํธ ๋
ธ๋๊ฐ ๋๊ณ head
,body
๋ ์์๋
ธ๋๊ฐ ๋๊ณ ๊ทธ ๋ฐ์ผ๋ก ๋ ์์๋ค์ด ๋ค๋ฌ๋ถ๋๋ค. ํ๊ทธ๋ ์์ ๋
ธ๋๊ฐ ๋๊ณ ํธ๋ฆฌ๊ตฌ์กฐ๋ฅผ ํ์ฑํ๋ค. ๋ฌธ์๋ ํ
์คํธ ๋
ธ๋๊ฐ ๋๋ค. ์ด ์ธ์ HTML ๋ด์ ๋ชจ๋ ๊ฒ์ DOM์ ๊ตฌ์ฑํ๋ค. ์ฌ์ง์ด ์ฃผ์๊น์ง ๋๋ค.
Javascript๋ ์ด๋ฌํ DOM์ ์์๋ค์ ๋ํด์ ์ ๊ทผํ ์ ์๋ ์ธ์ด์ด๊ณ , ๊ทธ ์์์ document
๊ฐ์ฒด์์ ์์ํ๋ค. document ๊ฐ์ฒด๋ ๊ทธ ์์ฒด๊ฐ html ํ์ด์ง ํ๋๋ฅผ ์๋ฏธํ๋ค.
<html> = document.documentElement
<body> = document.body
<head> = document.head
document.body.childNodes๋ iterable ์ ์ฌ๋ฐฐ์ด๊ฐ์ฒด์ธ collection์ด๋ค.
ํด์ ์ด๊ฑธ๋ก for๋ฌธ์ ๋๋ฉด์ ๊ฐ์ฒด์ ์์ฑ์ ๋ณ๊ฒฝํ๋ ์์
๋ ๊ฐ๋ฅํ๋ค.
๋ง์ฝ ๋ฐฐ์ด์ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๊ณ ์ถ์ผ๋ฉด
Array.from(document.body.childNodes).filter ์ ๊ฐ์ ์์ผ๋ก ์ฌ์ฉํ ์ ์๋ค.
DOM ์์ ์ฐพ๊ธฐ#
getElementByID, getElementsBy*#
๋ค์ ๋์ค๋ ํ๋กํผํฐ๋ฅผ ์ด์ฉํด์ ํด๋น ๋ ธ๋๋ฅผ ์ฐพ์์ฃผ๋ ๋ฉ์๋
getElementsBy
๋ก ์ฐพ์์จ ๊ฒ๋ค์ live ์ปฌ๋์ ์ด๋ค. ๋ฌธ์์ ๋ณ๊ฒฝ์ด ์์ ๋๋ง๋ค ์๋ ๊ฐฑ์ ๋์ด ์ต์ ์ํ๋ฅผ ์ ์งํ๋ค.
querySelector ํ๊ธฐ๋ฒ#
.class
html์์์ class ์ด๋ฆ์ ๊ธฐ๋ฐ์ผ๋ก ์์๋ฅผ ์ ํํ๋ ์ ํ์
ํด๋น ํด๋์ค๋ฅผ ๊ฐ์ง ๋ชจ๋ ์์๋ฅผ ์ ํํ๋ค - ๋ง์น
querySelectorAll(class)
์ฒ๋ผ์ฌ๋ฌ ํด๋์ค๋ฅผ ๋์์ ์ง์ ํ๋ ค๋ฉด ๊ณต๋ฐฑ์ผ๋ก ๊ตฌ๋ถ
์ ๋ฐ ๋ฐฉ์์ผ๋ก css ํ์ผ ๋ด๋ถ์์๋ ์ ์๋๋ค.
#id
id๋ document๋ด์์ ๊ณ ์ ํด์ผํ๋ค
๋ณดํต ํ๋์ ์์์ ๋ํด ๊ณ ์ ํ ์๋ณ์๋ก ์ฌ์ฉ๋๋ค.
:nth-child(n) elem
์์์ ์ ํํ ์์๋ค ์ค n๋ฒ์งธ๋ฅผ ์ ํ
DOM๊ธฐ๋ฐ node ๊ฒ์ methods
method |
search |
์์ ํธ์ถ |
collection๊ฐฑ์ |
---|---|---|---|
|
|
โ |
- |
|
|
โ |
- |
|
|
- |
- |
|
|
- |
โ |
|
|
โ |
โ |
|
|
โ |
โ |
์์๋๋ฉด ์ข์ methods
method |
do |
---|---|
|
์ผ์นํ๋์ง ์ฌ๋ถ ๊ฒ์ฌ |
|
๊ฐ์ฅ ๊ฐ๊น์ด ์กฐ์์์ ํ์ |
|
elemB๊ฐ elemA์ ์ํ๊ฑฐ๋, elemA==elemB์ผ๋ ์ฐธ ๋ฐํ |
DOM ์์ ๋ณ๊ฒฝํ๊ธฐ#
toggle#
DOM์ ํ๋์ class๋ง ๊ฐ์ง๊ณ ์์ง ์์ ํ๋ฅ ์ด ๊ต์ฅํ ๋๋ค. ํด๋น ํด๋์ค๊ฐ ์์ผ๋ฉด ๊ทธ ํด๋์ค๋ฅผ ์ถ๊ฐํ๊ณ ์์ผ๋ฉด ์์๋ค(๋ง์น ์ค์์น์ฒ๋ผ).
const h1 = document.querySelector("div.hello:first-child h1");
function handleTitleClick(){
// const clickedClass = "clicked";
// if (h1.classList.contains(clickedClass)){
// h1.classList.remove(clickedClass);
// } else {
// h1.classList.add(clickedClass);
// }
h1.classList.toggle("clicked")
}
h1.addEventListener("click",handleTitleClick);