How to check exact text in list a using jQuery?

I have a list a:

<div class='label'> <a>Menu</a> <a>Menu Food</a> <a>Menu Drink</a> <a>Cheese</a> </div> <div class="mytext"> this text need hide. </div> 

How can I check the list a above has the exact text = "Menu".

I used this script, but it does not work:

  $('.label a').filter(function(){ if($.trim($(this).text()) == "Menu"){ $('.mytext').show(); } else { $('.mytext').hide(); } }); 

I also can not use for loop and use the condition inside.

Thank you very much.

+5
source share
3 answers

Updated violin .

You can apply the operation to all matched anchors using return:

 return $.trim($(this).text()) == "Menu"; 

If you want to show the div only if there is an anchor with the text Menu , you can use the flag ( menu_exist in my example) in this state, then show if true :

 var menu_exist=false; $('.mytext').hide(); $('.label a').filter(function(){ if($.trim($(this).text())=="Menu"){ menu_exist=true; } }); if(menu_exist){ $('.mytext').show(); } 

Hope this helps.

 var menu_exist=false; $('.mytext').hide(); $('.label a').filter(function(){ if($.trim($(this).text())=="Menu"){ menu_exist=true; } }); if(menu_exist){ $('.mytext').show(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='label'> <a>Menu</a> <a>Menu Food</a> <a>Menu Drink</a> <a>Cheese</a> </div> <br> <div class="mytext"> this text need hide. </div> 
+2
source

Use $.trim($(this).text()) != "Menu" to select all items that are not Menu , and then use hide() on them.

 $('.label a').filter(function(){ return $.trim($(this).text()) != "Menu"; }).hide(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='label'> <a>Menu</a> <a>Menu Food</a> <a>Menu Drink</a> <a>Cheese</a> </div> 
+1
source

I played a little :-) and used . filter () function

The second form of this method allows us to filter elements against and not by a selector. For each element, if the function returns true (or a "true" value), the element will be included in the filtered set; otherwise it will be excluded

 var list = $('.label a').filter(function() { return $.trim($(this).text()) === "Menu" }); console.log(list.length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='label'> <a>Menu</a> <a>Menu Food</a> <a>Menu Drink</a> <a>Cheese</a> <a>Menu</a> </div> 
+1
source

Source: https://habr.com/ru/post/1261449/


All Articles