开发者

How to select parent element with an active (say) class inside a class of elements in JQuery?

开发者 https://www.devze.com 2022-12-29 16:01 出处:网络
I think this example would make it clear. My HTML is this: <li class=\'nav-active\'><span class=\'maillink\' id=\'spnInbox\' >Inbox</span></li>

I think this example would make it clear. My HTML is this:

 <li class='nav-active'><span class='maillink' id='spnInbox' >Inbox</span></li>
 <li><span class='maillink' id='spnSentMail'>Sent Mail</span></li>
 <li><span class='maillink' id='spnDraft'>Draft</span></li>
 <li><span class='maillink' id='spanTrash'>Trash</span></li>

When the user clicks on any other link say开发者_运维问答 Draft then I want to clear the nav-active from inbox "li" and assign that class to draft "li". My question is how to get to nav-active li from .maillink click event. I know I can write an each function and remove it but I was wondering if there is a selector to do this.

Thanks for your help.


use the siblings method to get the sibling with the nav-active class and clear the class.

next assign this class to the clicked element.

this gets to the parent li, then finds li siblings having the class nav-active, and removes the class from there. next applies the class to the parent of the clicked span.maillink element.

$(".maillink").click(function() {
    $(this).parent("li").siblings(".nav-active").removeClass("nav-active");
    $(this).parent("li").addClass("nav-active");
});​


Use closest method then siblings. This will walk parents of a given element until it finds the first LI item and then find the sibling li.nav-active element.

$(".maillink").click(function(e) { $(this).closest("li").siblings("li.nav-active");  } );


In click handler:

jQuery (this).parent().siblings('.nav-active').removeClass ('nav-active');
jQuery (this).parent().addClass('nav-active');


$(".maillink").click(function(){ $(this).parents("nav-active li").DoRestOfCode(); });

I think that was what you were asking.

0

精彩评论

暂无评论...
验证码 换一张
取 消