jQuery .closest(), .parent() or .parents()

In your page, you may have DOM trees, like <ul><li>…</li>…</ul>,  <tr><td>…</td>…</tr>, and so on.

Sometimes, we want to find out who is the parent of current DOM elements. .closest(), .parent() and .parents() methods are similar in that they both traverse up the DOM tree.

  1. .closest(): will return the first matched element in the DOM tree
  2. .parent(): travels a single level up the DOM tree
  3. .parents(): will search through the ancestors of current elements in the DOM tree, and return the closest parent to the outer ones.

For example, in blow DOM tree

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>
$( “li.item-1” ).closest(“ul”) will be “ul.level-3”
$( “li.item-1” ).closest(“li”) will be “li.item-1”, itself 🙂
$( “li.item-1” ).parent() will be “ul.level-3”
$( “li.item-1” ).parents() will be “ul.level-3”, “li.item-b”, …
In most case, closest() will return result in the fastest way.
Advertisements

About qianggan

Sr. Software Engineer
This entry was posted in Computers and Internet, jQuery. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s