开发者

Applying classes to a parent element with JS

I need to apply a class to the <li> tag that encloses an anchor tag when a user clicks on the link. Like this:

<ul>
<li><a href="#">Just an Example</a></li>
</ul>

So when the user clicks on <a href="#">Just an Example</a>, I need to apply a cl开发者_开发技巧ass to the <li> enclosing it. How would I target this? I am using jquery.


$('a[href=#]').click(function(){
   $(this).closest('li').addClass('your_class_name');
});

If its guaranteed that the parent element of such an anchor is a LI you might also use

$(this).parent().addClass('your_class_name');


just use

$('a').click(function(){
    $(this).parent().addClass('theClass');
});


$("a").click(function() {
   $(this).parent().whateveryouwant();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜