简体   繁体   中英

Find distant parent in jquery

I'm a little stuck on how to track down an element that's up the tree as a parent element.

$('.btn-action').hover(
  function(){
    $(this).find('.product-card').addClass('animated bounce');
  },
  function(){
    $(this).find('.product-card').removeClass('animated bounce')
  }
);

The .product-card class is not the direct parent but further up the tree. I need animate it based on the hover method on the .btn-action class. Can this be achieved with .parent() or .find() ?

To go up the tree you can use .closest().

$(this).closest('.product-card').addClass('animated bounce');

To go further in the tree use .find(). To stay on the same level, you can use .siblings()

Although I am not sure about the space in your classname. Try using a dash if multiple classes wasn't intended.

我认为,您可以使用.closest( selector )方法来获取元素的最近父级。

Have you tried using .parents()? @see https://api.jquery.com/parents/

To get the .product-card ancestors try:

$('.product-card').parents()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM