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