Using jQuery to search for specific text, add the class to the next UL

So, I am trying to add a class to UL depending on the text used in navigation.

For example.

<li> <a href="#">Text</a> <ul> </ul> </li> 

I want to add a class to ul depending on the text inside the tag, to find the text that I just use: contains a method

 $('#nav > li > a:contains("text")') 

After that, I draw a space on how to add the class to the next line, I thought .next might work, but it turns out that it is not.

Any help would be greatly appreciated!

+7
source share
6 answers

So how:

 $('#nav > li > a:contains("Text") + ul') 

? If <ul> could be anywhere after this, use:

 $('#nav > li > a:contains("Text") ~ ul') 

. Edit: In addition, the Text body is erroneous. :contains case sensitive (as other users have pointed out).

+2
source

That should work. Remember that it is case sensitive:

 $('#nav > li > a:contains("Text")').next().addClass('testClass'); 
+3
source

If you correctly understood that your next one will not disappear, because you did not select the jquery object. do something like

 $('#nav > li > a').each(function(){ if(yourCondition){ $(this).next('ul').addClass('yourClass'); } }); 
0
source

You do not select the a element to begin with.

The case must match:

 $('#nav > li > a:contains("Text")') 
0
source

PS: Matching "text" with "text" does not get any matches.

Do it..

$('#nav > li > a:contains("Text")').next('ul').addClass('my-new-class');

.. :)

0
source

As mentioned above, the cover text must be the same in order to get a positive result when choosing.

Try the following:

 <!DOCTYPE html> <html> <head> <title>example</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script> <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/themes/start/jquery-ui.css" rel="Stylesheet" type="text/css" /> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js" type="text/javascript"></script> <style type="text/css"> ul.square {list-style-type:square; font-size:x-large;} </style> <script type="text/javascript"> $(document).ready(function () { $('#nav li a:contains("Text")').siblings('ul').addClass("square"); }); </script> </head> <body> <ul id="nav"> <li>some item</li> <li>another item <a href="#">uninteresting link</a> <ul> <li>sublist item</li> </ul> </li> <li><a href="#">Text</a> <ul> <li>Special List</li> </ul> </li> </ul> </body> </html> 
0
source

All Articles