NickyTheWrench NickyTheWrench - 4 months ago 9
Javascript Question

Why won't this DIV hide using jQuery?

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.

JsFiddle

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.

Answer

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>