LoginSignup
0
0

More than 3 years have passed since last update.

【復習】JavaScriptで複数のclassに反映させる方法

Posted at

困ったこと

classを指定しているのに一つしか反映されない。。。

理解と対応

classの場合は配列になるので一つ一つ取り出さなければいけない

そんな時に利用するのが
for文

for (  初期値;  繰り返す条件;  増減値  ) {
  // 繰り返す処理を書く
}

配列の取り出し方としては
box[1]やbox[2]などで取り出すため
変数を用いてbox[i]と記載しfor文で変数の値を増やしていけば取り出すことが可能

実際のコード


<style>
    .box1  {
        width: 100px;
        height: 100px;
        background: red;
    }


    .box2 {
        width: 100px;
        height: 100px;
        background: red;
    }
</style>


<body>
    <div class="box1" id="jj"></div>
    </br>
    <div class="box2" id="hh"></div>
    </br>
    <div class="box2" id="hh"></div>

<script>
 var box = document.getElementsByClassName('box2');
 for (var i = 0 ; i < box.length ; i++ ){
  box[i].style.background = 'pink';
 }
</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