Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery add class to parent element

I have to set a class name on a (li) element. This script find all the (a) elements in the list, and creates a click event.

jQuery("#" + ElementID).find(TagName).click(function () {      GetPageByUrl(jQuery(this).attr("href"));     jQuery(this).parent().addClass('yourClass');     //ChangeSelectedMenuItem(this);     return false; }); 

The parent of every (a) element is a (li) element

But nothing happens when this line is executing jQuery(this).parent().addClass('yourClass');

Everything else is working just fine.

What am I doing wrong here?


Okay, but it still won't work. It won't add any class jQuery(this).addClass('yourClass'); Should add a class to the (a) element, but it doesn't?

like image 770
Alex Sleiborg Avatar asked Aug 14 '10 08:08

Alex Sleiborg


People also ask

What is the difference between parent () and parents () methods in jQuery?

parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.

How do I add a class to an element in CSS?

addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.


2 Answers

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass'); 

Or:

jQuery(this).parents('li').addClass('yourClass'); 
like image 171
Sarfraz Avatar answered Oct 23 '22 14:10

Sarfraz


$(this.parentNode).addClass('newClass');
like image 38
Delan Azabani Avatar answered Oct 23 '22 13:10

Delan Azabani