「JavaScript」add(remove)メソッドでクラスを追加/削除するサンプル

環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.62

構文
element = document.querySelector(selectors);
selectors
DOMString で、照合する 1 つ以上のセレクターを設定します。
戻り値
Element オブジェクトで、文書内で指定された CSS セレクターに最初に一致する要素を示すオブジェクト、
もしくは、一致する要素がない場合は null を返します。

書式
const 変数名 = document.querySelector(セレクター名);
CSSを追加
変数名.classList.add(css名);

CSSを削除
変数名.classList.remove(css名);

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<style>
.cft {
width: 120px;
height: 80px;
border: 1px solid #000;
}
.test {
font-size: 14px;
background-color: SkyBlue;
}
</style>
<script>
function add() {
 //要素cftの取得
const cft = document.querySelector(".cft");
//addメソッドで指定のCSSを追加
cft.classList.add("test");
}
function del() {
 //要素cftの取得
const yy = document.querySelector(".cft");
// CSSを削除
yy.classList.remove("test");
}
</script>
<div class="cft">test data</div>
<input type="button" value="追加" onclick="add()" />
<hr/>
<input type="button" value="削除" onclick="del()" />
</body>
</html>
<!DOCTYPE html> <html> <body> <style> .cft { width: 120px; height: 80px; border: 1px solid #000; } .test { font-size: 14px; background-color: SkyBlue; } </style> <script> function add() {  //要素cftの取得 const cft = document.querySelector(".cft"); //addメソッドで指定のCSSを追加 cft.classList.add("test"); } function del() {  //要素cftの取得 const yy = document.querySelector(".cft"); // CSSを削除 yy.classList.remove("test"); } </script> <div class="cft">test data</div> <input type="button" value="追加" onclick="add()" /> <hr/> <input type="button" value="削除" onclick="del()" /> </body> </html>
<!DOCTYPE html>
<html>
<body>
<style>
  .cft {
    width: 120px;
    height: 80px;
    border: 1px solid #000;
  }
  .test {
    font-size: 14px;
    background-color: SkyBlue;
  }
</style>


<script>
  function add() {
   //要素cftの取得
    const cft = document.querySelector(".cft");
    //addメソッドで指定のCSSを追加
    cft.classList.add("test");
  }
  function del() { 
   //要素cftの取得
    const yy = document.querySelector(".cft");
    // CSSを削除
    yy.classList.remove("test");
  }
</script>

<div class="cft">test data</div>
<input type="button" value="追加" onclick="add()" />
<hr/>
<input type="button" value="削除" onclick="del()" />

</body>
</html>

実行結果
「追加」ボタンを押すと、addメソッドで指定のCSSを追加します。
「削除」ボタンを押すと、removeメソッドで指定のCSSを削除します。

JavaScript

Posted by arkgame