Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to find certain text, then add class onto the following UL

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!

like image 891
rizzy Avatar asked Nov 28 '11 23:11

rizzy


People also ask

What is the jQuery script to add a class to an element?

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.

How do you check if an element has a specific class in jQuery?

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".

What is text () in jQuery?

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).

How do you append a class in Javascript?

Using . add() method: This method is used to add a class name to the selected element. Syntax: element.


2 Answers

This should work. Remember contains is case sensitive:

$('#nav > li > a:contains("Text")').next().addClass('testClass');
like image 92
xbrady Avatar answered Sep 30 '22 03:09

xbrady


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).

like image 22
Ry- Avatar answered Sep 30 '22 03:09

Ry-