Xereoth
Xereoth

Reputation: 31

jQuery: How to add div class "selected" on image click?

HTML:

<div class="result">
    <div class="bigCover">
        <a href="http://oreilly.com/catalog/0636920018001/">
            <img src= "img/cat_noCover.gif" alt= "HTML5: The Missing Manual, First Edition" class="book">
        </a>
    </div>
    <div class="cover">
        <img src="img/bkt_noCover.gif" class="book">
    </div>
</div>

When i click on the image i would like to add the class selected to the div with class result. But i can't get it to work using jQuery.

i got this as jQuery code now after trying some things.

$("img").click(function() 
{
    $(this).parent().addClass( "selected" );
});​

It works/starts on document.ready

Upvotes: 1

Views: 715

Answers (2)

Somnath Kharat
Somnath Kharat

Reputation: 3610

try this:

$("img").click(function() //$("img .book").click(function() more accurate selector
{
    $('.result').addClass("selected");
});​

if you have more then one element with class result then you can target it more accurate using:

$("img").click(function() //$("img .book").click(function() more accurate selector
{
    $(this).parent().prev('.result').addClass( "selected" );
});​

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82251

try this:

$(this).parent().prev().addClass( "selected" );

Working Demo

Upvotes: 1

Related Questions