π μμμμ cssν΄λμ€λ₯Ό μΆκ°, μ κ±°, μ ν
νλλ° μ μ©νκ² μ°μΈλ€.
π μ μμ±μ μ½κΈ° μ μ©μ΄μ§λ§, add()
λ° remove()
λ©μλλ₯Ό μ¬μ©νμ¬ μμ ν μ μλ€
π© add β‘ 1κ° λλ μ¬λ¬κ°μ class μμ±μ μΆκ°
document.getElementById("myDIV").classList.add("mystyle"); document.getElementById("myDIV").classList.add("mystyle", "anotherClass"); document.getElementById("myDIV").classList.add("mystyle", "anotherClass", "thirdClass");
μμ
<body> <button onclick="myFunction()">Try it</button> <div id="myDIV"> I am a DIV element </div> <body>
<style> .mystyle { width: 500px; height: 50px; padding: 15px; border: 1px solid black; } .anotherClass { background-color: coral; color: white; } .thirdClass { text-transform: uppercase; text-align: center; font-size: 25px; } </style>
<script> function myFunction() { document.getElementById("myDIV").classList.add("mystyle", "anotherClass", "thirdClass"); } </script>
π© remove β‘ 1κ° λλ μ¬λ¬κ°μ class μμ±μ μ κ±°
document.getElementById("myDIV").classList.remove("mystyle"); document.getElementById("myDIV").classList.remove("mystyle", "anotherClass"); document.getElementById("myDIV").classList.remove("mystyle", "anotherClass", "thirdClass"); // κΈ°μ‘΄ μ μ©λμ΄ μλ μμ± μ€μμ λΉΌκΈ°
μμ
<body> <button onclick="myFunction()">Try it</button> <div id="myDIV" class="mystyle"> I am a DIV element </div> <body>
<style> .mystyle { width: 500px; height: 50px; padding: 15px; border: 1px solid black; } </style>
<script> function myFunction() { document.getElementById("myDIV").classList.remove("mystyle"); } </script>
π© toggle β‘ λ class ν΄λμ€ κ°μ μ ν μ κ±°
document.getElementById("myDIV").classList.toggle("newClassName");
μμ
<body> <button onclick="myFunction()">Try it</button> <div id="myDIV" class="mystyle"> I am a DIV element </div> <body>
<style> .mystyle { width: 300px; height: 50px; background-color: coral; color: white; font-size: 25px; } .newClassName { width: 400px; height: 100px; background-color: lightblue; text-align: center; font-size: 25px; color: navy; margin-bottom: 10px; } </style>
<script> function myFunction() { document.getElementById("myDIV").classList.toggle("newClassName"); } </script>
π μμμ class μ΄λ¦μ κ°μ Έμ€κΈ°
.
<div id="myDIV" class="mystyle anotherClass thirdClass">I am a DIV element</div> let x = document.getElementById("myDIV").classList;
π μμμ μλ class μ΄λ¦ μ νμΈ
νκΈ°.
let x = document.getElementById("myDIV").classList.length;
π μμμ 첫 λ²μ§Έ ν΄λμ€ μ΄λ¦ (μΈλ±μ€ 0)
μ κ°μ Έμ€κΈ°.
let x = document.getElementById("myDIV").classList.item(0);
π μμμ "mystyle"ν΄λμ€κ° μλμ§ νμΈ
νκΈ°.
let x = document.getElementById("myDIV").classList.contains("mystyle");
π μμμ "mystyle"ν΄λμ€κ° μλμ§ μμλ³΄κ³ , μλ€λ©΄ λ€λ₯Έ ν΄λμ€ μ΄λ¦μ μ κ±°ννκΈ°
let x = document.getElementById("myDIV"); if (x.classList.contains("mystyle")) { x.classList.remove("anotherClass"); } else { alert("Could not find it."); }