Reputation: 39
I have a list of tag <p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
<p>Paragraph 10</p>
<p>Paragraph 11</p>
<p>Paragraph 12</p>
<p>Paragraph 13</p>
I have nth paragraph, and want to divide them into 2 part in order to style them differently in <div>
tag. How can I do that
e.g:
<div class="Top">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
</div>
<div class="Bottom">
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
<p>Paragraph 10</p>
<p>Paragraph 11</p>
<p>Paragraph 12</p>
<p>Paragraph 13</p>
</div>
Upvotes: 1
Views: 178
Reputation: 6606
If it's something you do a lot here is a more advanced approach which add a jQuery function called makeGroups()
.
Demo: JSnippet
The Plugin:
$.fn.makeGroups = function(n,c) {
c = c || [];
n = n > 0 ? n : 1;
len = this.length;
l = Math.floor(len / n);
l += (len - l * n > l)?1:0;
pc = "", p = 0, t = l;
for(var i = 0; i < n; i++) {
t += (len - l < t)?len - l:0;
gclass = (typeof c[i] != 'undefined')?c[i]:pc;
this.slice(p,t).wrapAll("<div class='" + gclass + "'></div>");
p = t, t = l + p, pc = gclass;
if (t > len) break;
}
return this;
};
Usage:
$('body p').makeGroups(2,["Top","Bottom"]);
Definition and Behavior:
Takes two arguments n, c
the first argument indicates how many groups you want. The second is a class name array which will be added to each group.
n
default is 1;c
is optional and if not set no class will be added.c
is smaller than the number of groups the last class will be used for the undefined class names.Upvotes: 0
Reputation: 1
Try using :lt()
, :not()
var p = $("p"), len = p.length;
$("body").prepend("<div class=Top></div><div class=Bottom></div>");
$(".Top").append($("p:lt("+ Math.floor(len / 2) +")"));
$(".Bottom").append($("p:not(.Top > p)"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<p>Paragraph 6</p>
<p>Paragraph 7</p>
<p>Paragraph 8</p>
<p>Paragraph 9</p>
<p>Paragraph 10</p>
<p>Paragraph 11</p>
<p>Paragraph 12</p>
<p>Paragraph 13</p>
Upvotes: 0
Reputation: 12173
You can use a combination of slice
and wrapAll
var $els = $("p");
var len = $els.length;
$els.slice(0, len / 2).wrapAll($("<div class='top' />"));
$els.slice(len / 2, len).wrapAll($("<div class='bottom' />"));
Upvotes: 2
Reputation: 28455
You can try something like following
var length = $('p').length;
$('p').slice(0,length/2).wrapAll("<div class='Top'></div>");
$('p').slice(length/2,length).wrapAll("<div class='Bottom'></div>");
Upvotes: 2