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?
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.
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.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
$(this.parentNode).addClass('newClass');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With