CLiown
CLiown

Reputation: 13843

jQuery - Hide table if it contains 1 <tr> and 1 <td> containing  

I've got a table that looks like this:

<table>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>

How can a i structure a jQuery selector in such a way that it will look for a table with a cell containing &nbsp; and set the table to display: none;

Help please?

Upvotes: 0

Views: 948

Answers (3)

Guidhouse
Guidhouse

Reputation: 1426

This will work according to specs and is still pure Jquery:

$('table tr:only-child td:only-child').filter(function () {
         return $(this).html() === '&nbsp;';}).closest("table").hide();

What troubled me was the special character in the table. Otherwise it would be simpler.

<table>
  <tr>
    <td>nbsp</td>
  </tr>
</table>

<script type="text/javascript">
    $('table tr:only-child td:only-child:contains("nbsp")').closest("table").hide();
</script>

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359786

$('table').each(function ()
{
    var $table = $(this),
        numTRs = $table.find('tr').length,
        $tds = $table.find('td'),
        numTDs = $tds.length;

    if (numTRs === 1 && numTDs === 1 && $tds.html() === '&nbsp;')
    {
        $table.hide();
    }
});

Test cases: http://jsfiddle.net/mattball/WhAcB/

Upvotes: 4

Nalum
Nalum

Reputation: 4213

Have a look at the following

$('table').each(function() {
    var $this = $(this);
    var trCount = $this.find('tr').length;
    var tdCount = $this.find('td').length;

    if (trCount == 1 && tdCount == 1) {
        var tdContents = $this.find('td:first').html();
        if (tdContents == '&nbsp;') {
            setTimeout(function() {
                $this.hide();
            }, 2000);
        }
    }
});

Upvotes: 0

Related Questions