LoginSignup
0
0

More than 1 year has passed since last update.

javascriptでid属性やclass属性を制御する

Posted at

■状況

もともと、バックエンドばかりを担当していた。
フロントも任されることになり、javascriptで制御をする必要があった。
情報はあったが、ばらけているのでシェアしたいと思った。

■ソース

ボタンの活性・非活性の制御をもとに、id属性とclass属性の例をあげる。

idの場合

この場合だと、1つのhtml要素しか制御できない。

<button type="button" id="download-button">ダウンロードする</button>


<script>
    // ボタンの表示・非表示を切替える
    const id = "download-button";
    const downloadButton = document.getElementById(id);
    if(isFileDownloadable === false){
      downloadButton.disabled = true;
    } else {
      downloadButton.disabled = false;
    }
</script>

classの場合

複数の同名のhtml要素を制御できる

<button type="button" class="download-button">ボタン1</button>
<button type="button" class="download-button">ボタン2</button>
<button type="button" class="download-button">ボタン3</button>

<script>
  // ボタンの表示・非表示を切替える
  const name = "download-button";
  // getElementsByClassNameで取得すると配列として格納される
  let buttons = document.getElementsByClassName(name);
    for(let i=0;i<buttons.length;i++){
      if(isFileDownloadable === false){
        buttons[i].setAttribute("disabled", true);
      } else {
        buttons[i].removeAttribute("disabled");
      }
    }
</script>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0