Reputation: 3230
I have a div
- I need to hide this div
if a td
on the same page contains some text.
In this case - if the td
says "Shipping" - I want the div
to be hidden. It doesn't seem to work.
Here is my code:
jQuery(function($) {
if ('#TBL1 table tr').has('td:contains("Shipping")') {
$("#myDiv").hide();
} else {
// code to be executed if condition is false
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="TBL1" class="ShipEst">
<table align="right" style="width: 100%">
<tbody>
<tr>
<td align="left">
<b>Subtotal: </b>
</td>
<td align="center"></td>
<td align="right">
<nobr>25.00</nobr>
</td>
</tr>
<tr>
<td align="left">
<b>Shipping: </b>
</td>
<td align="center"></td>
<td align="right">
<nobr>0.00</nobr>
</td>
</tr>
</tbody>
</table>
</div>
<div id="myDiv">
Hide this if td contains "Shipping"
</div>
I'm trying to do this with jQuery. Any help is appreciated.
Upvotes: 0
Views: 67
Reputation: 60543
As @Vohuman said you need .length
to read the property, otherwise it will always return true.
And the issue for start was the missing $
in your if
statement
$(document).ready(function() {
if ($('#TBL1 table tr td').has(':contains("Shipping")').length) {
$("#myDiv").hide();
} else {
// code to be executed if condition is false
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="TBL1" class="ShipEst">
<table align="right" style="width: 100%">
<tbody>
<tr>
<td align="left">
<b>Subtotal: </b>
</td>
<td align="center"></td>
<td align="right">
<nobr>25.00</nobr>
</td>
</tr>
<tr>
<td align="left">
<b>Shipping: </b>
</td>
<td align="center"></td>
<td align="right">
<nobr>0.00</nobr>
</td>
</tr>
</tbody>
</table>
</div>
<div id="myDiv">
Hide this if td contains "Shipping"
</div>
Upvotes: 2
Reputation: 144659
There are 2 problems in your code:
Syntax errors. The syntax of the if
statement should be:
if ( $('#TBL1 table tr').has('td:contains("Shipping")') ) {
.has
returns a filtered jQuery object. An object is always a truthy value in JavaScript, even for jQuery collections that have no elements. You need to read the .length
property of the returned collection:
if ( $('#TBL1 table tr').has('td:contains("Shipping")').length ) {
Upvotes: 3
Reputation: 471
You forgot to select #TBL1 as JQuery selector. Do this:
if($('#TBL1 table tr').has('td:contains("Shipping")')){
$("#myDiv").hide();
}
else {
// code to be executed if condition is false
}
Upvotes: -1