views:

32

answers:

4

Hello,

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-->
A: 
$('div.newsitems h3 a').click(function() {
    $(this).parent().parent().addClass('first');
});
Dustin Laine
This won't work if the structure changes at all.
SLaks
Good point, I saw your post is the best +1.
Dustin Laine
+2  A: 

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');
});
SLaks
`closest` is a life saver.
Mark
yes Mark, that s saved mine, too :) thx SLaks
Ahmet Kemal
A: 

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.

Mark
This won't work - the <a> tag contains another tag.
SLaks
@SLaks good point, but just change the "a" to "img" and it would :)
Mark
A: 

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');
Ahmet Kemal