Reputation: 39
How would I go about using wrap() to wrap following elements inside a <div>
?
For example:
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
etc
I'm wanting to wrap a <div>
around the tr, so the result would be:
<div>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</div>
<div>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</div>
<div>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</div>
Upvotes: 0
Views: 65
Reputation: 115272
The resulting markup is not a valid since permitted parent elements for tr
tags are <table>
, <thead>
, <tbody>
or <tfoot>
element.
Anyway, you can achieve the result by using nextUntil()
method.
// get all tr with main class and then
// iterate over them
$('.main').each(function() {
// get elements upto next `.main` element
$(this).nextUntil('.main')
// include current element
.add(this)
// wrap with div
.wrapAll('<div/>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr class="main"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</table>
Upvotes: 2
Reputation: 448
Answer # 1: As you expected
var parent = $('<div>');
$('tr.main').each(function() {
var child = $('<div>');
child.append($(this).nextUntil('tr.main'));
parent.append(child);
});
Answer # 2: Wrap with a table inside the div to avoid invalid mark up.
var parent = $('<div>');
$('tr.main').each(function() {
var table = $('<table>');
table.append($(this).nextUntil('tr.main'));
parent.append(table);
});
Upvotes: 0