LoginSignup
1
1

More than 5 years have passed since last update.

CSSセレクタで指定した複数イベントターゲット要素の共通/限定処理

Last updated at Posted at 2018-06-14

div.itemがいくつかあるが、いずれかclickした対象だけを青くして他を赤くしたい。

See the Pen querySelectorAll and forEach by pokkur (@pokkur) on CodePen.

js
const item = document.querySelectorAll('.item')

Array.prototype.forEach.call(item, (e) => {
    e.addEventListener('click', (e) => {
        Array.apply(null, item).forEach((e) => e.style.background = `hsl(358, 100%, 62%)`) // clickされてないitemは赤く
        e.currentTarget.style.background = `hsl(196, 100%, 53%)` // clickされたitemは青く
    }, false)
})

どなたか、これもっと使い勝手良いヘルパーとかつくってださい……。

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