3
4

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.

【脱jQuery】closestをネイティブのjavascriptで書く

Last updated at Posted at 2018-08-30

はじめに

大変便利なjQueryメソッド closest()
脱jQuery して 簡易的ではありますが、javascript のみで書いていきたいと思います。

jQuery

jQuery
$('.selector').closest('.targetClass');

javascript

javascript
const closest = (el, targetClass) => {
  for (let item = el; item; item = item.parentElement) {
    if (item.classList.contains(targetClass)) {
      return item
    }
  }
}

closest(document.body.querySelector('.selector'), 'targetClass')

.item クリック時に先祖要素である .wrapper_inner を取得して class demo を追加したいと思います。

html
<div class="wrapper">
  <div class="wrapper_inner">
    <ul class="items">
      <li class="item">item</li>
      <li class="item">item</li>
      <li class="item">item</li>
      <li class="item">item</li>
      <li class="item">item</li>
    </ul>
  </div>
</div>
javascript
const closest = (el, closestClass) => {
  for (let item = el; item; item = item.parentElement) {
    if (item.classList.contains(targetClass)) {
      return item
    }
  }
}

const items = [].slice.call(document.body.querySelectorAll('.item'))

items.forEach((item) => {
  item.addEventListener('click', (e) => {
    const closestEl = closest(e.currentTarget, 'wrapper_inner')

    if (!closestEl) {
      return
    }

    closestEl.classList.add('demo')
  })
})

まとめ

最近、一部のブラウザでは Element.closest() 実装済で Polyfill もありますので、利用シーンに応じて使い分けていただければと思います。

最後まで閲覧いただきありがとうございました!

3
4
1

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?