LoginSignup
13
14

More than 5 years have passed since last update.

parent()・parents()・closest()の違い

Posted at

ある要素の上の階層にある要素を取得するメソッドの違いを説明します。

メソッドの概要

  • parent([selector]) : 1個上の階層の要素を取得
  • closest(selector) : セレクタに合致する、直近の階層の要素を取得
  • parents([selector]) : 上の階層の全ての要素を取得

実行してみる

ChromeDeveloperToolsなどにコピペして実際に指定してみてくださいね

<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-3.1.0.min.js"></script>
</head>
<body>
  <div id="parent-a">
    <h1>見出し</h1>
    <div id="parent-b">
      <div id="parent-c">
        <div id="child"></div>
      </div>
    </div>
  </div>
</body>
</html>

$('#child').parent(); 
  -> [<div id="parent-c">..</div>]

$('#child').closest('#parent-c'); 
  -> [<div id="parent-c">..</div>]

$('#child').parents(); 
  -> [<div id="parent-c">..</div>, <div id="parent-b">..</div>, <div id="parent-a">..</div>, <body>..</body>, ..]

parent()とclosest()の違い

  • parent() : 1個上の階層の要素しか取得できない
    • 上の例だと、$('#child')からは、parent-cしか取れない
  • closest() : 1個上とは限らず、条件に合致する最も近い階層の要素を取得できる
    • 上の例だと、$('#child').closest('parent-b')などで、親の親要素であるparent-bを取ることもできる
13
14
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
13
14