Thomas
Thomas

Reputation: 5089

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 class to the <li> enclosing it. How would I target this? I am using jquery.

Upvotes: 1

Views: 62

Answers (3)

Matschie
Matschie

Reputation: 1247

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

Upvotes: 1

rob waminal
rob waminal

Reputation: 18419

just use

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

Upvotes: 1

jAndy
jAndy

Reputation: 236002

$('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');

Upvotes: 2

Related Questions