Reputation: 323
There have been a few situations where I'm trying to generate content, but the elements are siblings. So, I want to generate tags that are siblings, and then just append 1 element to the actual DOM to reduce DOM calls.
For example (starting with element generation):
var tr = $('<tr>');
var td = $('<td>')
.append( $('<label>Label 1</label>') )
.append( "some text" );
tr.append(td);
var tr2 = $('<tr>');
var td2 = $('<td>')
.append( $('<label>Label 2</label>') )
.append( "other text" );
tr2.append(td2);
This would generate something that looks like this for the first tr element:
<tr>
<td>
<label>Labe 1</label>
some text
</td>
</tr>
and the second element would look similar. This is fine, but my question is is there a way to add the second to the first and then only have to append the first to the actual table in the dom?
Looking to do something like:
$('#someTable').append( /*append 1 thing instead of both tr's*/ );
The idea is to reduce calls to the actual DOM, if there are tons of elements.
Note: I realize that document.createElement is way faster than $('create element')
Upvotes: 0
Views: 64
Reputation: 9647
There are different ways of achieving this. I would suggest the preferred method is to use detach on your table, do your DOM manipulation (add a bunch of <tr>
s), then re-add it to your DOM. This is actually the method described in jquery performance.
I had originally suggested using insertAfter or after as solutions for this question, but one of the OP's requirements is to avoid creating an "intermediate" parent. Both of these methods are therefore not valid solutions. I have since improved the above solution.
Upvotes: 1
Reputation: 24648
Since ideally tr elements are children of tbody you could add all tr's to tbody then finally add the one tbody to the table:
var tbody = $('<tbody/>');
tbody.append( tr )
.append( tr2 );
Upvotes: 0
Reputation: 78740
You can simply use add
to create a new collection containing the elements from both collections. For instance:
tr = tr.add(tr2);
After this, tr
would now contain both rows. You could then append them at once:
$("#someTable").append(tr); // add all rows contained in tr
Upvotes: 2