1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでfor文(foreach)内でのgetElementsByClassNameの使用法

Last updated at Posted at 2020-01-03

##はじめに
趣味で作っているツイッタークローンにおいて、ツイート一覧にマスオーバーさせると背景色が変化するjsの処理を書きたかった。

##JSをあてるPHPファイル

3行目のtweetcardが対象のclass名です。
注)実際は生のphpファイルではなくテンプレートエンジンのbladeを使用しています。

home.php
@if ($posts)
  @foreach($posts as $post)
    <div class="card tweetcard">
      <div class="card-body alert tweet">
        {{ $post->name }}
        {{ $post->created_at }}
        <br>
        {{ $post->content }}
      </div>
    </div>

##間違った書きかた

samle.js
const tweetcard = document.getElementsByClassName('tweetcard');

  //クリックイベントで背景色を変える
  tweetcard.addEventListener('mouseenter', () => {
      tweetcard.style.backgroundColor  = "#e6ecf0";
  }, false);

}
  //クリックイベントで背景色を戻す
  tweetcard.addEventListener('mouseleave', () => {
      tweetcard.style.backgroundColor = "white";
  }, false);
}

エラーが出ました。
リファレンスを確認してみます。下記抜粋。

getElementsByClassName メソッドは、指定されたクラス名をすべて持つすべての子要素の配列風オブジェクトを返します。 引用元:MDN web docs

getElementsByClassNameで取得した要素は配列だったのですね!

だったらfor分で回してあげればいいですね。

##正しい書き方

samle.js
const tweetcard = document.getElementsByClassName('tweetcard');

//mouseenter
for(let i = 0; i < tweetcard.length; i++){

  //クリックイベントで背景色を変える
  tweetcard[i].addEventListener('mouseenter', () => {
      tweetcard[i].style.backgroundColor  = "#e6ecf0";
  }, false);

}
//mouseenter
for(let i = 0; i < tweetcard.length; i++){

  //クリックイベントで背景色を戻す
  tweetcard[i].addEventListener('mouseleave', () => {
      tweetcard[i].style.backgroundColor = "white";
  }, false);
}

これでマウスをかざした領域の背景色が変更され、マウスを外せば背景色が元に戻るようになりました。

##参考
MDN web docs

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?