DO YOU NEED A CONTENT WRITER FOR YOUR BUSINESS?

Your One-Stop Solution for All Content Needs! Click here for more!
Categories: jQuery

Difference between .closest() and .parents()

Share

Using jQuery closest and parents, you can set or get the first or all ancestor element that matches the selector and traversing up through its ancestors in the DOM tree.

The ancestor may be a parent, grandparent, great grandparent, and so on.

For example:

$("div").closest("p").css({"color": "red"});

If it doesn’t match the selector, then it will continue traversing up the document, parent by parent until the element is found which matches the specified expression.

If no matching element is found, then none will be returned.

Get more about .closest() from jQuery documentation.

Whereas, the parents() method returns all ancestor elements of the selected element.

In the same way, the ancestor is a parent, grandparent, great grandparent, and so on.

For example:

$("div").parents("p").css({"color": "red"});

Get more about .parents() from jQuery documentation.

Read Also: jQuery unwrap() – Remove wrapping div

This method is similar to jQuery closest(), in that they both traverse up the DOM tree.

But, the differences are as follows:

closest() :

  • Begins with the current element.
  • Returned jQuery object contains zero or one element.
  • It travels up the DOM tree and then returns the first ancestor which matches the passed expression.

parents() :

  • Begins with the parent element.
  • Returned jQuery object contains zero or more than one element.
  • It travels up the DOM tree and then returns all ancestors which matches the passed expression.
Namaste UI

For any types of queries, you can contact us on info[at]namasteui.com.

Recent Posts

Flawless Prize Fulfilment and Management That Takes Your Marketing Campaigns to the Next Level

In today’s fast-paced and highly competitive marketing environment, even the most creative campaign is only…

1 day ago

Moving company Zeromax in NYC

We are NYC moving firm. Are you planning a flat move? Maybe a distance or…

5 days ago

Mobile testing: An important task for smooth functioning of the device

Mobile devices, unlike desktops and laptops, can not be handled by dozens or hundreds of…

6 days ago

Augmented Reality in Education is Blowing Up the Candles!

Augmented Reality- An immersive experience for the learners! Learning and education aren’t the same as…

1 week ago

Here Are 4 Diamond Studs for You to Gift Your Special Ones

On special days like birthdays and weddings, we all like to celebrate our loved ones…

1 week ago

7 Best Web Application Development Tools

A web application is different from a regular mobile or desktop application as it runs…

1 week ago