The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody
for example:
<table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
You would end up with the following:
<table id="myTable">
<tbody>
<tr>...</tr>
<tr>...</tr>
</tbody>
<tr>...</tr>
</table>
I would therefore recommend this approach instead:
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
You can include anything within the after()
method as long as it's valid HTML, including multiple rows as per the example above.
Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody
in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody
unless you have specified one yourself.
DaRKoN_ suggests appending to the tbody
rather than adding content after the last tr
. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody
elements and the row would get added to each of them.
Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.
I think the safest solution is probably to ensure your table
always includes at least one tbody
in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody
elements):
$('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');
Since the question refers to a single element, this code might be more suitable:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.
We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.
Best Answer
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a
<span>
, provided you keep the class attribute with it.By the way, I think you could do it in one selector:
If that makes things easier.