Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my hidden <tr> not really hidden?

Tags:

jquery

visible

I have this simple html markup generated from classic asp:

<table>
  <tr class="trClass">
    <td>Hello </td>
  </tr>
  <tr class ="trClass">
    <td>World!</td> 
  </tr>
</table>

If i set the tr belonging to Hello to hide() using Jquery it hides. Good!

But, when i use this $('.trClass:visible').each(function() { alert('visible') }); it shows the output 'visible' twice.

Why is this?

My problem here is that im filtering a table on a column with a selection box. But after filtering i need to perform some calculations on those rows that are visible in the table, but i get all rows right now.

Any ideas?

/Daniel

like image 990
Daniel Svensson Avatar asked Sep 28 '09 11:09

Daniel Svensson


People also ask

How do I hide the tr tag?

The hidden attribute hides the <tr> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <tr> element is not visible, but it maintains its position on the page.

How to hide a tr in JavaScript?

Use jQuery's toggle() Function to Hide Table Rows in JavaScript. The example will take table rows and set them to display: "none" . And when clicked to a certain anchor tag, it will redefine the current stage to display: "block" .

How to make row invisible in html?

I add style="display:none;" to my table rows all the time and it effectively hides the entire row.


1 Answers

The :visible selector does not test the display style property, you want to use :hidden instead, the 1.3.2 release notes say:

...if your element's CSS display is "none", or any of its parent/ancestor element's display is "none", or if the element's width is 0 and the element's height is 0 then an element will be reported as hidden.

These will correctly select your visible rows:

$('.trClass:not(:hidden)').each(function() { 
    alert('visible'); 
});

or:

$('.trClass').each(function() { 
    if(!$(this).is(':hidden')) {
        alert('visible'); 
    }
});

or:

$('.trClass').filter('not:(:hidden)').each(function() { 
    alert('visible');
});

hide sets the style to display="none". The release notes for jQuery 1.3.2 also say:

In jQuery 1.3.2 an element is visible if its browser-reported offsetWidth or offsetHeight is greater than 0.

so I guess in this case the :visible selector is erroneously not matching anything because the rows are not occupying any space according to the calculations performed, despite the fact that their CSS display property is not set to none. Conversely, :hidden correctly matches elements with style="display:none" so testing for non :hidden elements works just fine.

like image 68
karim79 Avatar answered Oct 06 '22 13:10

karim79