2
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 3 years have passed since last update.

[JavaScript] DOM 要素の照合

Last updated at Posted at 2020-05-27

概要

  • ある DOM 要素を照合する API の忘備録です。

  • 以下の3メソッドについて解説してます。

    1. element.contains(element)
    2. element.closest(selector)
    3. element.matches(selector)

element.contains(element)

  • 要素A と 要素B の親子関係を調べます。
<div id="parent">
  <span id="child">8^-^8</div>
  <div><span id="grand-child">8^-^-^8</span></div>
</div>

<span id="friend">=^-^=</div>
const parentNode = document.getElementById('parent')
const childNode = document.getElementById('child')
const grandchildNode = document.getElementById('grand-child')
const friendNode = document.getElementById('friend')

parentNode.contains(childNode)  // true
parentNode.contains(grandchildNode)  // true
parentNode.contains(friendNode)  // false
parentNode.contains(parentNode)  // true

parentNode.contains(null)  // false
parentNode.contains(undefined)  // false

element.closest(selector)

  • ある要素の祖先要素の内、selector にマッチする直近要素を返します。
<h1>Title</h1>

<section class="root">
  <div class="message">
    <div class="target">8^-^8</div>
  </div>
</section>
const targetElement = document.getElementById('target')

targetElement.closest('.message')  // <div class="message">
targetElement.closest('.root')  // <div class="root">
targetElement.closest('h1')  // null

element.matches(selector)

  • 指定要素が CSS セレクタにマッチするかどうかを論理値で返します。
<div id="apple">🍎🍎🍎</div>
<div id="banana">🍌🍌🍌</div>
<div id="banana-fresh" class="fresh">🍌🍌🍌</div>
const apple = document.getElementById('apple')
const banana = document.getElementById('banana')
const bananaFresh = document.getElementById('banana-fresh')

apple.matches('#apple')  // true
apple.matches('#banana')  // false

banana.matches('#banana')  // true
banana.matches('#banana.fresh')  // false

bananaFresh.matches('.fresh')  // true
bananaFresh.matches('#banana.fresh')  // true
2
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
2
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?