I got one HTML file containing a table:
src.Html:
<table id="all">
<tr>
<th>Row 1</th>
<td>Content 1</td>
</tr>
<tr>
<th>Row 2</th>
<td>Content 2</td>
</tr>
<tr>
<th>Row 3</th>
<td>Content 3</td>
</tr>
</table>
And here is my code:
$('document').ready(function(){
var tempTable = $('<table id="tempTable"></table>');
tempTable.load('src.Html #all tr');
console.log(tempTable); --> it shows content of tempTable
console.log($(tempTable).find('tr')); --> it shows []
});
it’s works, and it prints the content of tempTable.
But when I want to get row based on needs, it shows nothing!
Such as:
$(tempTable).find('tr'); --> []
$(tempTable).find('tr').eq(1); --> []
$('#tempTable tr:eq(2)') --> []
Can anyone tell me why? Is that tempTable not a normal DOM object?
I personally dislike the .load method. I’ve always been struggling with it. I don’t even know why this example doesn’t properly load and display the HTML. However, I did do some testing in there. See for yourself.
Within the callback, it’s all fine. The callback is executed after the calls to the same functions outside of the callback. That means your content is loaded after your code, hence you receive empty arrays.
The reason why you still are showed, in the Google Chrome Developer Tool, par example, that temp table has the children, is that you have a reference to a DOM object. I believe the difference is that the JavaScript scope is different from the DOM scope. Unlike pure JavaScript objects, every reference I’ve so far had to a DOM object is automatically updated. See in this revision. Both references to the same table show that the third row has a different content although they are called at different times.
Concluding, all you need is a callback handler.
Edit:
Forget about why it wouldn’t show the contents. Of course it wouldn’t, I never updated them.