Programing Language/Javascript

[Javascript] getElement*, querySelector*๋กœ ์š”์†Œ ์ ‘๊ทผํ•˜๊ธฐ

JHeaon ใƒป 2023. 3. 18. 01:27



๐Ÿ“š getElement*, querySelector*๋กœ ์š”์†Œ ์ ‘๊ทผํ•˜๊ธฐ 

 

DOM ํƒ์ƒ‰ ํ”„๋กœํผํ‹ฐ๋ฅผ ์‚ฌ์šฉํ•ด ๋ชฉํ‘œ ์š”์†Œ์— ์‰ฝ๊ฒŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๐Ÿ”– DOM : Document Object Model๋กœ ์›นํŽ˜์ด์ง€๋ฅผ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋กœ ์ œ์–ดํ•˜๊ธฐ ์œ„ํ•œ ๊ฐ์ฒด ๋ชจ๋ธ์„ ์˜๋ฏธํ•œ๋‹ค. 

 

 

๐Ÿ“’document.getElement* ์„ ํ†ตํ•ด ์š”์†Œ ๊ฒ€์ƒ‰ํ•˜๊ธฐ

 

์š”์†Œ์— id ์†์„ฑ์ด ์žˆ์œผ๋ฉด ์œ„์น˜์— ์ƒ๊ด€์—†์ด ๋ฉ”์„œ๋“œ document.getElement* ์„ ํ†ตํ•ด ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. 

 

<div id="elem">
  <div id="elem-content">Element</div>
</div>

<script>
  // ์š”์†Œ ์–ป๊ธฐ
  let elem = document.getElementById('elem'); // ์š”์†Œ ์ ‘๊ทผ

  // ๋ฐฐ๊ฒฝ์ƒ‰ ๋ณ€๊ฒฝํ•˜๊ธฐ
  elem.style.background = 'red';
</script>

 

 

 

 

๐Ÿ“’document.querySelector* ์„ ํ†ตํ•ด ์š”์†Œ ๊ฒ€์ƒ‰ํ•˜๊ธฐ

 

document.querySelector* ์ฃผ์–ด์ง„ CSS ์„ ํƒ์ž์— ๋Œ€์‘ํ•˜๋Š” ์š”์†Œ ์ค‘ ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์„ ์›ํ•œ๋‹ค๋ฉด, document.querySelectorAll ์„ ์ด์šฉํ•œ๋‹ค. 

 

<ul>
  <li>1-1</li>
  <li>1-2</li>
</ul>
<ul>
  <li>2-1</li>
  <li>2-2</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child'); // ์š”์†Œ ์ ‘๊ทผ

  for (let elem of elements) {
    alert(elem.innerHTML); // "1-2", "2-2"
  }
</script>

 

 

 

 

'Programing Language/Javascript'์˜ ๋‹ค๋ฅธ๊ธ€

  • ํ˜„์žฌ๊ธ€ [Javascript] getElement*, querySelector*๋กœ ์š”์†Œ ์ ‘๊ทผํ•˜๊ธฐ

๊ด€๋ จ๊ธ€