rookiee
rookiee

Reputation: 13

jquery selecting closest div

Categories div is hidden and i want it to be shown when toggler is hovered. Any help would be appreciated.

html

<div class="categorization">
 <a href="#" class="toggler">something</a>

 <div class="categories">
 </div>

</div>

i tried this.

jquery

  $(".categorization .toggler").hover(function() {
   $(this).closest('.categories').show();
  }, function(){
   $(this).closest('.categories').hide();
  });

Upvotes: 1

Views: 9653

Answers (3)

Liangliang Zheng
Liangliang Zheng

Reputation: 1785

Note that :

In jquery API,

.closest() : Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

Apparently, your <div> element is not an ancestor element of <a>

see http://api.jquery.com/closest/

In this case, you should try .next(), if you want to get only one element, or .nextAll(), if you want to get all elements matches your selector.

Upvotes: 0

bdparrish
bdparrish

Reputation: 2764

var categoryDiv = $(this).next('div'); // or
var categoryDiv = $(this).next('.categories');

this will get you the next div sibling relative to toggler.

Upvotes: 3

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262929

closest() walks the ancestor tree, so it's not what you're looking for. You can use nextAll() and first() to achieve what you want:

$(".categorization .toggler").hover(function() {
    $(this).nextAll(".categories").first().show();
}, function(){
    $(this).nextAll(".categories").first().hide();
});

Note that next() only matches the very next element, so next(".categories") will only work if the <div> element immediately follows your toggler element.

Upvotes: 5

Related Questions