Hiding rows related to empty rows using jquery
I have a table structure for displaying posts like this:
<table>
<tr><td>heading of the post</td></tr>
<tr><td>body of the post</td></tr>
</table>
I want to hide both rows if the body's content happens to be empty.
How can I achieve this using jquery?
Forgot to mention the body contains images that are removed if 开发者_如何学JAVAthey didn't load correctly $("img").error(function(){ $(this).remove(); });
but when I check the source the html is still there so maybe it is not being considered as empty
There are a number of ways to do this.
$('td').each(function() {
if($(this).html()=='') {
$(this).parent().hide()
}
})
To get the previous row:
$(this).parent().prev().hide()
This should do the trick:
$('td').filter(function () {
return $.trim($(this).html()) == '';
}).closest('tr').prev().remove().end().remove();
The problem with :empty
is that it has to be completely empty - no whitespace.
Also note that changing the page through JavaScript won't affect the page source, which represents the original HTML. You will need to use an element inspector provided by Firebug or Chrome's Developer Tools to view the "live" state of the page.
Slightly off topic, but I don't see why using a table structure is necessary. You can make your markup both more meaningful, and easier to work with:
<article>
<h1>Heading of the post</h1>
<p>Body of the post</p>
</article>
Then the jQuery can be simplified to:
$('article p').filter(function () {
return $.trim($(this).html()) == '';
}).closest('article').remove();
Find a row with an empty column and then hide it.
$('tr:has(td:empty)').hide();
精彩评论