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:


In the example above:

  • The .closest() method is called on '.example-class-one' 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.



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.


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).


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.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?