Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check exact text in list a using Jquery?

Tags:

html

jquery

I have 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 list a above has 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 cannot use for loop and use condition inside.

Thank you very much.

like image 814
Hai Tien Avatar asked Dec 18 '16 11:12

Hai Tien


3 Answers

Updated fiddle.

You could apply operation for all the matched anchors using return :

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

If you want to show the div just if there's an anchor with Menu text you could use a flag (menu_exist in my example) in the condition 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>
like image 89
Zakaria Acharki Avatar answered Nov 12 '22 20:11

Zakaria Acharki


Use $.trim($(this).text()) != "Menu" to select all the elements which is 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>
like image 23
Rajshekar Reddy Avatar answered Nov 12 '22 20:11

Rajshekar Reddy


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

The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns true (or a "truthy" 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>
like image 1
jyrkim Avatar answered Nov 12 '22 21:11

jyrkim