tags:

views:

31

answers:

1

hello all,

var rows = $(".sometable tr:last");
var cells = $(".sometable tr:last td").filter(function() { return $(this).html().length == 0 });

i want to get first empty cell in the last row of my table.

the table is rendered from the server and it is html table. i can iterate to cells and get the first cell if there are elements available. But i do not want to do that.

Is there any other way without looping. After getting first element i want to call jquery .html('set') method to set soem html data.

A: 
$('.sometable tr:last td:empty:first')

However, :last and :first are non-standard jQuery-specific selectors which means you won't get the benefit of fast native selectors. Also, you're going to have trouble if there can be nested tables.

If you make sure you've got a <tbody> around the rows in your markup (for XHTML and browser fixup compatibility), you could better say:

$('.sometable>tbody>tr:last-child>td:empty')[0]
bobince
does .empty works for white spaces also?
komg
does that return null in any case?
komg
but i am not able to call $('.sometable>tbody>tr:last-child>td:empty')[0].html() method; i want to call that... i dont want to use .innerHTML
komg
As with your original code, `:empty` won't match if there's a whitespace text node inside the element. (Careful: IE can throw away whitespace nodes, which other browsers won't.) You also should avoid putting a comment in the cell, as `:empty` is supposed to ignore comments, but jQuery/Sizzle's implementation of it doesn't.
bobince
OK, if you want the jQuery wrapper version, `$('.sometable>tbody>tr:last-child>td:empty').eq(0)`; it's the same thing.
bobince
(Careful: IE can throw away whitespace nodes, which other browsers won't.) what does this means
komg
When IE parses `<td> </td>` in the original document, it does not create a Text node inside the HTMLTableCellElement to contain the whitespace. It just throws it away, which is a bug. When you are dealing with whitespace cross-browser, you have to allow for this, either by making sure the empty `<td>` never has any whitespace in it, or by going back to your original `filter` style of selection and making sure to trim the HTML before comparing it to an empty string.
bobince
but that will be too slow then your way,
komg
It would be slower, yes. How much slower and whether that matters depends on how complicated your document is. But yeah, I'd try to make sure the empty cells were really empty if I could, so that `:empty` would work consistently both as a jQuery selector and when using plain old CSS.
bobince