designerNProgrammer
designerNProgrammer

Reputation: 2701

grabbing the closest element

i am working on a gallery where i need to add a class to image when the overlay div is hovered.

this is my html

 <div class="overlayForCarDetails"></div>
 <a href="img/car_details/1large.jpg" rel="shadowbox">
   <img class="mediumImg" src="img/car_details/1medium.jpg" alt="">
 </a>

And this is my javascript

        $('.overlayForCarDetails').mouseenter(function () {
            $(this).css('opacity', '0.7');
            $(this).closest('.mediumImg').addClass('zoomed');

        });

But somehow its not working. Can you tell me where am i doing it wrong. thanks.

Upvotes: 1

Views: 64

Answers (3)

Adil
Adil

Reputation: 148178

You need nextAll(), or siblings() to get the a elements at same level in the hierarchical tree of DOM. Then you need to using find() to get the .mediumImg in the descendants of a The closest() looks the ancestors of element on the DOM hierarchy.

$('.overlayForCarDetails').mouseenter(function () {
     $(this).css('opacity', '0.7');
     $(this).next('a').find('.mediumImg').addClass('zoomed');
});

next()

Description: Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

You have to use .next() and .find() instead of .closest() (as closest look up hierarchy), like below :

$('.overlayForCarDetails').mouseenter(function () {
            $(this).css('opacity', '0.7');
            $(this).next().find('.mediumImg').addClass('zoomed');

        });

Upvotes: 3

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to select the .next() sibling and .find() the relevant element from it.,

$(this).next('a').find('.mediumImg').addClass('zoomed');

Full code would be,

 $('.overlayForCarDetails').mouseenter(function () {
   $(this).css('opacity', '0.7');
   $(this).next('a').find('.mediumImg').addClass('zoomed');
 });

Upvotes: 3

Related Questions