Question

I am working on a Jquery accordion stuff. I want to add a class to the div that contains the accordion trigger <a> tag. You can look at my code. I want to add "first" class name to just first "newsitems" class when clicked "Recession fashion in Japan Video" title.

        <!-- news items starts-->
        <div class="newsitems">
          <h3 class="business"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Recession fashion in Japan Video</a> </h3>
          <p class="timestamp">0100hrs</p>
        </div>
        <!-- news items ends-->
        <!-- news items starts-->
        <div class="newsitems">
          <h3 class="sports"> <a href="#" title="expand"><img src="images/expand_icon.gif" alt="collapse" class="collpase" /> Murray survives five-set thriller at Wimbledon</a> </h3>
          <p class="timestamp">0100hrs</p>
        </div>
        <!-- news items ends-->
Was it helpful?

Solution

You're looking for the closest method, whch finds the innermost parent containing an element.

For example:

$('div.newsItems h3 a').click(function() { 
    $(this).closest('div.newsItems').addClass('first');
});

OTHER TIPS

$('div.newsitems h3 a').click(function() {
    $(this).parent().parent().addClass('first');
});

Also we should add something like below lines to remove class after clicking another trigger:

var dropDown = $(this).parent().next().next(); /* This is configured for my script. Yours may be different*/
$('div.newsitems').not(dropDown).removeClass('first');

Just for an alternative answer.

$('div.newsItems').click(function(e){
    if($(e.target).is("IMG")){
        $(this).addClass("first");
    }
}

Edit: Changed the if($(e.target).is("a")){ to IMG as SLaks pointed out that I missed that tag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top