jQuery closest div with specific class/id

Heiko M. picture Heiko M. · Apr 20, 2015 · Viewed 10.4k times · Source

I need your help.
This code works fine for me:

<div class="grauereihe">
    <div class="kleinesbild">
        <a data-lightbox="ags1" class="bildtopa" href="images/image1.jpg">
            <img class="bildtop" src="images/produkte/KHF/KHF-DN40-03-2.jpg" />
        </a>
    </div>
    <div class="infozeile">
        <div class="produkttext">
            <img class="kleinegalerie" src="images/image2.jpg" />
            <img class="kleinegalerie" src="images/image3.jpg" />
        </div>
    </div>
</div>


<script>
$('.produkttext img').on({
    'mouseover': function() {
        var images = $(this).attr('src');
        $('.bildtop').attr('src', images);
        $('.bildtopa').attr('href', images);
    }
});
</script>

but i need this code for more than one .grauereihe, like:

<div class="grauereihe">
    <div class="kleinesbild">
        <a data-lightbox="lb1" class="bildtopa" href="images/image1.jpg">
            <img class="bildtop" src="images/image1.jpg" />
        </a>
    </div>
    <div class="infozeile">
        <div class="produkttext">
            <img class="kleinegalerie" src="images/image2.jpg" />
            <img class="kleinegalerie" src="images/image3.jpg" />
        </div>
    </div>
</div>

<div class="grauereihe2">
    <div class="kleinesbild">
        <a data-lightbox="lb1" class="bildtopa" href="images/image1.jpg">
            <img class="bildtop" src="images/image1.jpg" />
        </a>
    </div>
    <div class="infozeile">
        <div class="produkttext">
            <img class="kleinegalerie" src="images/image2.jpg" />
            <img class="kleinegalerie" src="images/image3.jpg" />
        </div>
    </div>
</div>

So i thought of replace the src and href with closest-function (or parent), but I can't get it work. Like:

<script>
$('.produkttext img').on({
    'mouseover': function() {
        var images = $(this).attr('src');
        $(this).closest('img').find('.bildtop').attr('src', images);
        $(this).closest('a').find('.bildtopa').attr('href', images);
    }
});
</script>

Can anyone help me out? Thanks

Answer

Tushar picture Tushar · Apr 20, 2015

To get the first ancestor, you can use closest() method. As the closest() method gives you the closest ancestor and the element you're looking for is not an ancestor, you can traverse to the closest parent element and then use find() method to get the descendant element.

$('.produkttext img').on({
    'mouseover': function(){
        var images = $(this).attr('src');
        $(this).closest('.grauereihe').find('img.bildtop').attr('src', images);
        $(this).closest('.grauereihe').find('a.bildtopa').attr('href', images);
    }
});