So I am trying to add a class onto a UL depending on the text used in the navigation.
For example.
<li>
<a href="#">Text</a>
<ul>
</ul>
</li>
I want to add a class onto the ul depending on the text inside the a tag, to find the text I just use the a:contains method
$('#nav > li > a:contains("text")')
After that I draw a blank on how to add a class onto the ul that follows, I thought the .next might work but it turns out it doesn't.
Any help would be greatly appreciated!
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed).
Using . add() method: This method is used to add a class name to the selected element. Syntax: element.
This should work. Remember contains is case sensitive:
$('#nav > li > a:contains("Text")').next().addClass('testClass');
So, like:
$('#nav > li > a:contains("Text") + ul')
? If the <ul>
could be anywhere after that, use:
$('#nav > li > a:contains("Text") ~ ul')
. Edit: Also, Text
's casing is wrong. :contains
is case-sensitive (as others have pointed out now).
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