In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0
means false
, everything else true
. So you could write:
if ($(selector).length)
You don't need that >0
part.
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>');
Best Answer
If the functions should be globally accessible (which might indicate bad design of your application), then you have to define them outside the
ready
handler.See above.
Depends on what your JavaScript code is doing and where it is located. It the worst case you will get runtime errors because you are trying to access DOM elements before they exist. This would happend if your code is located in the
head
and you are not only defining functions but already trying to access DOM elements.There is no "harm" per se. It would just not work if the the script is located in the
head
, because the DOM elements don't exist yet. That means, jQuery cannot find and bind the handler to them.But if you place the script just before the closing
body
tag, then the DOM elements will exist.To be on the safe side, whenever you want to access DOM elements, place these calls in the
ready
event handler or into functions which are called only after the DOM is loaded.As the jQuery tutorial (you should read it) already states:
To give a more complete example: