์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- ํจ์
- like
- ๋ฐฑํฑ
- ํ ์ด๋ธ
- MySQL
- post๋ฐฉ์
- DATE_FORMAT
- ๋ฐฐ์ด
- ํ๋ก๊ทธ๋๋จธ์ค
- ์ปจํธ๋กค๋ฌ
- ๋ช ๋ น์ด
- JSP
- oracle
- Spring
- SQL
- JS
- Ajax
- ๋ฆฌ๋ ์ค
- order by
- ์ฝํ
- ๋์ปค
- ๋์ ํ ์ด๋ธ
- ์๋ฐ์คํฌ๋ฆฝํธ
- optionํ๊ทธ
- JavaScript
- ์ธ๋ผ์ธ๋ทฐ
- select
- ๋ณ์
- Update
- ๋์
- Today
- Total
bom's happy life
[JS] className ์์ฑ / getElementsByClassName๋ฉ์๋ ๋ณธ๋ฌธ
[JS] className ์์ฑ / getElementsByClassName๋ฉ์๋
bompeach 2023. 6. 3. 16:011. className ์์ฑ(property)
- `className `์ DOM ์์์ ํด๋์ค๋ฅผ ๋ํ๋ด๋ ์์ฑ์ด๋ค.
- ์์์ ํด๋์ค ์ด๋ฆ์ ๋ฌธ์์ด ํํ๋ก ๊ฐ์ ธ์ค๊ฑฐ๋ ์ค์ ํ ์ ์๋ค.
- ์๋ฅผ ๋ค์ด, <p> ์์๋ฅผ ์ ํํ๊ณ ํด๋น ์์์ className ์์ฑ์ ์ฌ์ฉํ์ฌ ํด๋์ค ์ด๋ฆ์ ๊ฐ์ ธ์ค๊ณ ๋ณ๊ฒฝํ๋ค. ์ด๊ธฐ ์ํ์์ <p> ์์์๋ "my-class"๋ผ๋ ํด๋์ค ์ด๋ฆ์ด ์๋ค. className ์์ฑ์ ํตํด ํด๋น ํด๋์ค ์ด๋ฆ์ ๊ฐ์ ธ์จ ํ, element.className = "new-class"์ ๊ฐ์ด ์ฌ์ฉํ์ฌ ํด๋์ค ์ด๋ฆ์ "new-class"๋ก ๋ณ๊ฒฝํ๋ค. ๋ณ๊ฒฝ๋ ํด๋์ค ์ด๋ฆ์ ํ์ธํ๊ธฐ ์ํด ๋ค์ console.log(element.className)์ ์ฌ์ฉํ์ฌ ์ถ๋ ฅํ๋ค. -> ๊ฐ : `new-class`
์ฌ์ฉ ์์ →
<body>
<p id="demo" class="my-class">Hello, World!</p>
<script>
// ์์ ๊ฐ์ ธ์ค๊ธฐ
var element = document.getElementById("demo");
// className ์์ฑ ์ฌ์ฉํ๊ธฐ
console.log(element.className); // "my-class"
// className ์์ฑ ๋ณ๊ฒฝํ๊ธฐ
element.className = "new-class";
// ๋ณ๊ฒฝ๋ className ํ์ธํ๊ธฐ
console.log(element.className); // "new-class"
</script>
</body>
2. getElementsByClassName ๋ฉ์๋(method)
- `getElementsByClassName ` ์ Document ๋๋ Element ์ธํฐํ์ด์ค์ ์ํ ๋ฉ์๋์ด๋ค.
- DOM์์ ํด๋์ค ์ด๋ฆ์ ๊ธฐ๋ฐ์ผ๋ก ์์๋ฅผ ์ ํํ๋ ๋ฉ์๋์ด๋ค.
- ์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํน์ ํด๋์ค๋ฅผ ๊ฐ์ง ๋ชจ๋ ์์๋ฅผ ์ ํํ ์ ์์ต๋๋ค.
- ์ด ๊ฐ์ฒด๋ ๋ฐฐ์ด๊ณผ ์ ์ฌํ๊ฒ ์ธ๋ฑ์ค๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋ณ ์์์ ์ ๊ทผํ ์ ์๋ค.
- ์๋ฅผ ๋ค์ด, ๋ฐ์ ์์์์๋ ํด๋์ค ์ด๋ฆ์ด "my-class"์ธ <div> ์์๋ค์ ์ ํํ๊ธฐ ์ํด getElementsByClassName("my-class")๋ฅผ ์ฌ์ฉํ๋ค. ๋ฐํ๋ ์์๋ค์ HTMLCollection์ผ๋ก ๋ฐํ๋๋ค. ๊ทธ๋ฐ ๋ค์ for ๋ฃจํ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐํ๋ ์์๋ค์ ์ ๊ทผํ๊ณ , ๊ฐ ์์์ textContent๋ฅผ ์ถ๋ ฅํ๋ค. ์ด ์์์์๋ ํด๋์ค ์ด๋ฆ์ด "my-class"์ธ 3๊ฐ์ <div> ์์๊ฐ ์์ผ๋ฉฐ, for ๋ฃจํ๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ ์์์ ๋ด์ฉ์ ์ถ๋ ฅํ๋ค. ์ถ๋ ฅ ๊ฒฐ๊ณผ๋ "Element 1", "Element 2", "Element 3" ๊ฐ ๋๋ค.
์ฌ์ฉ ์์ →
<body>
<div class="my-class">Element 1</div>
<div class="my-class">Element 2</div>
<div class="my-class">Element 3</div>
<script>
// ํด๋์ค ์ด๋ฆ์ผ๋ก ์์ ์ ํํ๊ธฐ
var elements = document.getElementsByClassName("my-class");
// ๋ฐํ๋ ์์๋ค์ ์ ๊ทผํ๊ธฐ
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
console.log(element.textContent);
}
</script>
</body>
.
.
.
์ ๋ฆฌํ์๋ฉด, `className` ์ ์์ฑ(property)์ผ๋ก์ ํน์ ์์์ ํด๋์ค๋ฅผ ์กฐ์ํ๋ ๋ฐ ์ฌ์ฉ๋๊ณ , `getElementsByClassName` ์ ๋ฉ์๋(method) ๋ก์ ํด๋์ค ์ด๋ฆ์ ๊ธฐ๋ฐ์ผ๋ก ์์๋ค์ ์ ํํ๋ ๋ฐ ์ฌ์ฉ๋๋ค!