Learn
Traversing the DOM
Closest

To select an element close to the current element, we can use jQuery’s .closest() method.

The .closest() method will travel up the DOM tree to find a specified selector closest to it. Its syntax looks like:

$('.example-class-one').closest('.another-class');

In the example above:

  • The .closest() method is called on '.example-class' elements.
  • The method then targets the element selected by the .closest() method with a class of '.another-class'.
<div class='.another-class'> <p class='.example-class-one'>1</p> </div> <div class='.another-class'> <p class='.example-class-two'>2</p> </div>

Given this HTML, the jQuery above would select the <div> element that wraps the paragraph with a value of 1, because it is the closest element, up the DOM tree, with the class .another-class.

Instructions

1.

In the Children exercise, you removed the 'disabled' class from all '.shoe-details' elements when a user clicked a size. When you did that, it activated the ADD TO CART button in every product details card.

Use the .closest() method to activate only the current product details ADD TO CART button.

Inside of the '.shoe-details li' click event handler, create a jQuery object with the current element and use .closest() to target the nearest '.shoe-details' element.

2.

Now that you’ve targeted the current '.shoe-details' card, use the .children() and .removeClass() methods to activate the current ADD TO CART button (remove the 'disabled' class).

3.

Next, we need to use the .closest() method to target the nearest shoe details element when a user selects a .more-details-button element.

Inside the '.more-details-button' click event handler’s callback function, write another $(event.currentTarget) selector. Then, call the .closest() method on it, and find the closest element with a class of '.product-details'.

In the next exercise, we will chain a .next() method to this.

Folder Icon

Sign up to start coding

Already have an account?