DOM - part2

jiseongยท2021๋…„ 8์›” 3์ผ
0

T I Learned

๋ชฉ๋ก ๋ณด๊ธฐ
17/291

Dom์„ ํƒ์ƒ‰ ํ•  ์ˆ˜ ์žˆ๋Š” property

๐Ÿ“ ์˜ˆ์‹œ ์ฝ”๋“œ

<div>
    <h1>Cities</h1>
    <ul>
        <li id="one" class="red">Seoul</li>
        <li id="two" class="red">London</li>
        <li id="three" class="red">Newyork</li>
        <li id="four">Tokyo</li>
    </ul>
</div>

1. parentNode โœ”๏ธ

  • parentNode๋Š” ํ•ด๋‹น ์š”์†Œ์˜ ๋ถ€๋ชจ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.
const element = document.querySelector('#one');
console.log(element.parentNode); /* parentNode */

2. firstChild, lastChild vs firstElementChild, lastElementChild โœ”๏ธ

  • ํ•ด๋‹น ์š”์†Œ์˜ ์ž์‹ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.

  • 1. firstChild, lastChild
const element = document.querySelector('ul');
console.log(element.firstChild); /* firstChild */
console.log(element.lastChild); /* lastChild */

  • child node๋ฅผ element node ๋˜๋Š” text node, comment node๋กœ ๋ฐ˜ํ™˜ โ—

  • ์—ฌ๊ธฐ์„œ๋Š” ul๊ณผ li ์‚ฌ์ด์— ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž๊ฐ€ ์žˆ์–ด text node๊ฐ€ ๋ฐ˜ํ™˜

โ“ ์ฐธ์กฐ
IE๋ฅผ ์ œ์™ธํ•œ ๋Œ€๋ถ€๋ถ„์˜ ๋ธŒ๋ผ์šฐ์ €๋“ค์€ ์š”์†Œ ์‚ฌ์ด์˜ ๊ณต๋ฐฑ ๋˜๋Š” ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž๋ฅผ ํ…์ŠคํŠธ ๋…ธ๋“œ๋กœ ์ทจ๊ธ‰ํ•˜๊ธฐ ๋•Œ๋ฌธ

  • 2. firstElementChild, lastElementChild
const element = document.querySelector('ul');
console.log(element.firstElementChild); /* firstElementChild */
console.log(element.lastElementChild); /* lastElementChild */

  • child node๋ฅผ element node๋งŒ์„ ๋ฐ˜ํ™˜(text์™€ comment node๋ฅผ ๋ฌด์‹œ) โ—

3. childNodes โœ”๏ธ

  • text node๋ฅผ ํฌํ•จํ•œ ๋ชจ๋“  ์ž์‹ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. (NodeList (non-live))

4. children โœ”๏ธ

  • ์ž์‹ ์š”์†Œ๋“ค ์ค‘์—์„œ Element nodes๋งŒ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. (HTMLCollection (live))

5. previousSibling, nextSibling vs previousElementSibling, nextElementSibling โœ”๏ธ

  • ํ•ด๋‹น ์š”์†Œ์˜ ์ด์ „๊ณผ ๋‹ค์Œ์˜ ํ˜•์ œ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.
  • 2. firstChild vs firstElementChild์™€ ๋™์ผํ•˜๊ฒŒ element node๋งŒ์„ ๋ฐ˜ํ™˜ํ•˜๋ƒ ์•„๋‹ˆ๋ƒ์˜ ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค.

Reference

0๊ฐœ์˜ ๋Œ“๊ธ€