DOM ์กฐ์
๊ฐ์
โ DOM ์กฐ์ ์์
- ์ ํ(select)
- ์กฐ์(maipulation)
์ ํ ๊ด๋ จ ๋ฉ์๋
document.querySelector(selector)
โ ์ ๊ณตํ ์ ํ์์ ์ผ์นํ๋ element ํ ๊ฐ ์ ํ
โ ์ ๊ณตํ CSS selector๋ฅผ ๋ง์กฑํ๋ ์ฒซ ๋ฒ์งธ element ๊ฐ์ฒด ๋ฐํ(์๋ค๋ฉด null ๋ฐํ)document.querySelectorAll(selector)
โ ์ ๊ณตํ ์ ํ์์ ์ผ์นํ๋ ์ฌ๋ฌ element๋ฅผ ์ ํ
โ ๋งค์นญํ ํ๋ ์ด์์ ์ ๋ ํฐ๋ฅผ ํฌํจํ๋ ์ ํจํ CSS selector๋ฅผ ์ธ์๋ก ๋ฐ๋๋ค.
โ ์ ๊ณตํ CSS selector๋ฅผ ๋ง์กฑํ๋ NodeList ๋ฐํ
์ ํ ๊ด๋ จ ๋ฉ์๋ ์ค์ต
<script>
console.log(document.querySelector("#title"));
console.log(document.querySelectorAll(".text"));
console.log(document.querySelector(".text"));
console.log(document.querySelectorAll("body > ul > li"));
liTags = document.querySelectorAll("body > ul > li");
liTags.forEach((element) => {
console.log(element);
});
</script>

NodeList
โ index๋ก๋ง ๊ฐ ํญ๋ชฉ์ ์ ๊ทผ ๊ฐ๋ฅ
โ ๋ฐฐ์ด์ forEach
๋ฉ์๋ ๋ฐ ๋ค์ํ ๋ฐฐ์ด ๋ฉ์๋ ์ฌ์ฉ ๊ฐ๋ฅ
โ querySelectorAll()์ ์ํด ๋ฐํ๋๋ NodeList๋ DOM์ ๋ณ๊ฒฝ์ฌํญ์ ์ค์๊ฐ์ผ๋ก ๋ฐ์ํ์ง๋ ์๋๋ค. (๊ธฐ๋ณธ์ ์ผ๋ก ๋์ ์ด์ง๋ง querySelectorAll()์ ์ํด ๋ฐํ๋ ๋๋ ์ ์ !)
์กฐ์ ๊ด๋ จ ๋ฉ์๋
์์ฑ: document.createElement(tagName)
โ ์์ฑํ tagName์ HTML ์์๋ฅผ ์์ฑํ์ฌ ๋ฐํ
์
๋ ฅ: Node.innerText
โ Node ๊ฐ์ฒด์ ๊ทธ ์์์ ํ ์คํธ ์ปจํ ์ธ (DOMstring)์ ํํ
์ถ๊ฐ: Node.appendChild()
โ ํ Node๋ฅผ ํน์ ๋ถ๋ชจ Node์ ์์ NodeList์ค ๋ง์ง๋ง ์์์ผ๋ก ์ฝ์
โ ํ๋ฒ์ ์ค์ง ํ๋์ Node๋ง ์ถ๊ฐ ๊ฐ๋ฅ
โ ์ถ๊ฐํ Node ๊ฐ์ฒด๋ฅผ ๋ฐํ
โ ๋ง์ฝ ์ฃผ์ด์ง Node๊ฐ ์ด๋ฏธ ๋ฌธ์์ ์กด์ฌํ๋ ๋ค๋ฅธ Node๋ฅผ ์ฐธ์กฐํ๋ค๋ฉด ํ์ฌ ์์น์์ ์๋ก์ด ์์น๋ก ์ด๋
์ญ์ : Noede.removeChild()
โ DOM ์์ ๋ ธ๋ ์ ๊ฑฐ
์กฐ์ ๊ด๋ จ ๋ฉ์๋ ์ค์ต
<script>
// ํ๊ทธ ์์ฑ
const h1Tag = document.createElement('h1')
// ํ๊ทธ์์ ์ปจํ
์ธ ๋ฅผ ์์ฑํ๊ณ
h1Tag.innerText = 'DOM ์กฐ์'
// ๋ถ๋ชจ div ํ๊ทธ๋ฅผ ๊ฐ์ ธ์์
const div = document.querySelector('div')
// div ํ๊ทธ์ ์์ ์์๋ก ์ถ๊ฐ
div.appendChild(h1Tag)
// div์ h1 ์์ ์ญ์
div.removeChild(h1Tag)
</script>
<script>
// a ํ๊ทธ ์์ฑ
const aTag = document.createElement('a')
// a ํ๊ทธ ์์ฑ ์ถ๊ฐ
aTag.setAttribute('href', 'https://google.com')
// a ํ๊ทธ ์ปจํ
์ธ ์ถ๊ฐ
aTag.innerText = '๊ตฌ๊ธ'
// div ํ๊ทธ ์ ํ ํ ์์ ํ๊ทธ๋ก a ํ๊ทธ ์ถ๊ฐ
const divTag = document.querySelector('div')
divTag.appendChild(aTag)
// hi ํ๊ทธ ์ ํ ํ ํด๋์ค ๊ฐ ์กฐ์
const h1Tag = document.querySelector('h1')
h1Tag.classList.toggle('blue')
</script>
์กฐ์๊ด๋ จ ๋ฉ์๋(์์ฑ ์กฐํ ๋ฐ ์ค์ )
โ Element.getAttribute(attributeName)
- ํด๋น ์์์ ์ง์ ๋ ๊ฐ(๋ฌธ์์ด)์ ๋ฐํ
- ์ธ์(attributeName)๋ ๊ฐ์ ์ป๊ณ ์ ํ๋ ์์ฑ์ ์ด๋ฆ
โ Element.setAttribute(name, value)
- ์ง์ ๋ ์์์ ๊ฐ์ ์ค์
- ์์ฑ์ด ์ด๋ฏธ ์กด์ฌํ๋ฉด ๊ฐ์ ๊ฐฑ์ , ์กด์ฌํ์ง ์์ผ๋ฉด ์ด๋ฆ๊ณผ ๊ฐ์ ์ ์์ฑ์ ์ถ๊ฐ
์์ฑ ์กฐํ ๋ฐ ์ค์ ์ค์ต


'โญ Personal_Study > Javascript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋๊ธฐ์ ๋น๋๊ธฐ (0) | 2022.11.04 |
---|---|
Callback & Promise (0) | 2022.11.04 |
JavaScript์์์ This (0) | 2022.11.03 |
Event (0) | 2022.11.02 |
DOM (Document Object Model) (0) | 2022.11.01 |
๋๊ธ