
๐ ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive ๋ด์ฉ์ ๋ฐํ์ผ๋ก ์์ฑํ์์ต๋๋ค.
getElementsByClassName์ผ๋ก ์์๋ฅผ ๊ฐ์ ธ์์, ํ๊ทธ ์์ ์๋ ๋ฌธ์์ด๋ค์ ์๋์ ๊ฐ์ ๋ฐฉ์์ผ๋ก ๊ฐ์ ธ์ฌ๋ ค๊ณ ํ ์ ์ด ์์๋๋ฐ, ์ด์ํ๊ฒ ๊ณ์ ์๋ฌ๊ฐ ๋ ์ ๊ฒฐ๊ตญ ๋ค๋ฅธ ๋ฉ์๋๋ฅผ ์ด์ฉํ ์ ์ด ์์๋ค.
const $class= document.getElementsByClassName("A"); $class.forEach((ele) => { console.log(ele.textContent); });
๊ทธ ๋น์์ ํ์ฐธ์ ๊ตฌ๊ธ๋งํ๋ค๊ฐ, ์ ์ฌ๋ฐฐ์ด์ด๋ผ์ forEach๋ฅผ ์ฌ์ฉํ์ง ๋ชปํ๋ค๋ ๊ฒ ๊น์ง๋ง, ์์๋ด๊ณ ๋ค์์ ๊ธฐ์ฝํ๋ฉฐ ๋
ธ์
์ ์ ์ด๋์์๋ค.
๊ทธ๋ฐ๋ฐ ์ค๋ getElementById, getElementsClassName, querySelector, querySelectorAll ์ ๊น๊ฒ ์ดํดํ์ง ์๊ณ , ์ฐ๊ณ ์๋ค๋ ์๊ฐ์ด ๋ค์ด ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ๋ฅผ ์ฝ๋ค๊ฐ, ์ ๋ถ๋ถ์ ๋ํ ํด๊ฒฐ๋ฐฉ๋ฒ์ ์๊ฒ ๋์๋ค.
์ผ๋จ ๋จผ์ HTMLCollection ๊ณผ NodeList ์ ์ฐจ์ด์ ๋ํด ์์๋ณด์!
HTMLCollection, NodeLists ๋ ๋๋ค ์ ์ฌ๋ฐฐ์ด๊ฐ์ฒด์ด๋ค. ์ ์ฌ ๋ฐฐ์ด์ด๊ธฐ ๋๋ฌธ์, ๋ฐฐ์ด์์ ์ ๊ณตํ๋ ๋ชจ๋ ๋ฉ์๋๋ฅผ ๊ฐ์ง๊ณ ์์ง ์์ต๋๋ค.
getElementsByTagName, getElementsByClassName ๋ฉ์๋๊ฐ ๋ฐํํ๋ ๊ฐ์ฒด์ด๋ค.
์๋ฅผ ๋ค์ด, class ๊ฐ์ด fruit์ธ ์์ ๋ ธ๋๋ฅผ ๋ชจ๋ ํ์ํด์ class ์ด๋ฆ์ red๋ก ๋ณ๊ฒฝํด๋ณด์.
<li class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="fruit">Orange</li>
const $elems = document.getElementsByClassName('fruit');
for (let i=0; i< $elems.length; i++)
{
$elems[i].className = 'red';
}
์ด๋ ๊ฒ ๊ตฌํํ๋ค๋ฉด class ์ด๋ฆ์ด ๋ณ๊ฒฝ๋ ๊ฒ ๊ฐ์ง๋ง, ๋๋ฒ์งธ li ์์๋ฅผ ์ ์ธํ ๋๋จธ์ง li์์๋ค์ class ์ด๋ฆ์ด ๋ณ๊ฒฝ๋๋ค.
๊ทธ ์ด์ ๋ ๋ ธ๋ ๊ฐ์ฒด์ ์ํ๋ณํ๋ฅผ ์ค์๊ฐ์ผ๋ก ๋ฐ์ํ๊ธฐ ๋๋ฌธ์ด๋ค.
์์ ์ฝ๋๋ฅผ ์ฒ์ฒํ ์ดํด๋ณด๋ฉด ๋จผ์ ,
(i == 0 ) ์ฒซ๋ฒ์งธ li์์์ ๊ฐ์ 'red'๋ก ๋ณ๊ฒฝ๋๋ค.
(i == 1 ) ๊ทธ๋ผ ์ฒซ๋ฒ์งธ ์์์ class ์ด๋ฆ์ด red๋ก ๋ณ๊ฒฝ๋๊ธฐ ๋๋ฌธ์,
์ฒซ๋ฒ์งธ ์์๋ ๊ฐ์ฒด์์ ์ ๊ฑฐ๋๋ค. ๊ทธ๋์ ์ธ๋ฑ์ค ๊ฐ์ด ๋ณ๊ฒฝ๋๊ฒ ๋๊ณ , ์๋๋
๋๋ฒ์งธ ์์์ธ Banana์ class ์ด๋ฆ์ด ๋ณ๊ฒฝ๋์ด์ผ ํ์ง๋ง, ์ฒซ๋ฒ์งธ ์์๊ฐ ์ญ์ ๋๋ฉด์, ๋๋ฒ์งธ ์์๊ฐ ์ฒซ๋ฒ์งธ ์์๋ก ๋ณ๊ฒฝ๋๊ณ , ์ธ๋ฒ์งธ ์์๊ฐ ๋๋ฒ์งธ ์์๋ก ๋ณ๊ฒฝ๋๋ฉด์, ์ธ๋ฒ์งธ ์์์ธ Orange์ class ์ด๋ฆ์ด ๋ณ๊ฒฝ๋๋ค.
(i == 2) Apple, Orange์ class ์ด๋ฆ์ด ๋ณ๊ฒฝ๋๋ฉด์, $elems ์์๋ Banana ์์๋ง ๋ค์ด์๋ค. $elems.length < i ๊ฐ ๋๋ฉด์, for๋ฌธ์ ์ข ๋ฃ๋๋ค.
๋ด๊ฐ ์์์ ์ธ๊ธํ ์ด์ ๋ฅผ ์ฐพ์ง๋ชปํ ์๋ฌ์ ์์ธ์ด๊ธฐ๋ ํ๋ค.
const $class= document.getElementsByClassName("A"); $class.forEach((ele) => { console.log(ele.textContent); });
๋๋ $class ๋ฅผ ๋ฐฐ์ด ๋ฉ์๋ forEach๋ฅผ ๋ฐ๋ก ์ฌ์ฉํ ๋ ค๊ณ ํ์ง๋ง, $class ๋ ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด์ด๊ณ , ์ผ๋ถ ๋ฐฐ์ด ๋ฉ์๋๋ ์ฌ์ฉ๊ฐ๋ฅํ์ง๋ง, HTMLCollection ๊ฐ์ฒด์ ๊ฒฝ์ฐ์๋ forEach ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์์๋ ๊ฒ์ด๋ค. ๊ทธ๋ผ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ๋ฌด์์ผ๊น?
const $class= document.getElementsByClassName("A");
[...$class].forEach((ele) => {
console.log(ele.textContent);
});
const $class= document.getElementsByClassName("A");
Array.from($class).forEach((ele) => {
console.log(ele.textContent);
});
querySelectorAll ๋ฉ์๋๊ฐ ๋ฐํํ๋ ๊ฐ์ฒด์ด๋ค.
๋จ ์ฐจ์ด์ ์ HTMLCollection์ forEach ๋ฉ์๋๋ฅผ ๋ณ๊ฒฝ์์ด ๋ฐ๋ก ์ฌ์ฉํ ์ ์์์ง๋ง, NodeList๋ ๋ณ๊ฒฝ์์ด ๋ฐ๋ก ์ฌ์ฉํ ์์๋ค.
๋๋จธ์ง๋ ์์์ ์ค๋ช
ํ HTMLCollectionc์ฒ๋ผ ๋๊ฐ์ง ๋ฐฉ๋ฒ์ผ๋ก NodeList ๊ฐ์ฒด๋ฅผ ๋ฐฐ์ด๋ก ๋ณํ ํ ๋ฐฐ์ด ๋ฉ์๋๋ค์ ์ฌ์ฉํ ์ ์๋ค.
๐ฅ ๋ง์ง๋ง์ผ๋ก HTMLCollection๊ณผ NodeList ๊ฐ์ฒด๋ ์์๊ณผ ๋ค๋ฅด๊ฒ ๋์ํ ๋๊ฐ ๋ง๊ธฐ ๋๋ฌธ์, ๋ ธ๋ ๊ฐ์ฒด์ ์ํ ๋ณ๊ฒฝ๊ณผ ์๊ด์์ด ์์ ํ๊ฒ ์ฌ์ฉํ๊ธฐ ์ํด ๊ฐ์ฒด๋ฅผ ๋ฐฐ์ด๋ก ๋ณํํ์ฌ ์ฌ์ฉํ๋ ๊ฒ์ ๊ถ์ฅํ๋ค๊ณ ํ๋ค.