I have a HTML code like this:
<li>one</li>
<li>two</li>
<li>era</li>
<li>jeu</li>
<li>iuu</li>
<li>iij</li>
<li>emu</li>
<li>our</li>
I need to wrap them into 2 element equally (or like 5:6 if total is 11), like this:
<ul>
<li>one</li>
<li>two</li>
<li>era</li>
<li>jeu</li>
</ul>
<ul>
<li>iuu</li>
<li>iij</li>
<li>emu</li>
<li>our</li>
</ul>
This should work on any amount of <li>
's. Can you suggest an elegant solution with jQuery?
var $li = $('li'),
half = Math.floor($li.length/2);
$li.filter(function(i){ return i < half; }).wrapAll('<ul>');
$li.filter(function(i){ return i >= half; }).wrapAll('<ul>');
You can divide by 2
and then round down or up (depending on whether you want 4:5
or 5:4
). After doing that, replace the li
s with a ul
containing the li
s (first clone them, because otherwise the li
s would have been moved around, and would not be able to be replaced because their original position is lost).
var li = $('li'),
amount = li.length,
left = amount / 2 | 0, // '| 0' rounds down
right = amount - left;
var leftElems = li.slice(0, left);
leftElems.replaceWith($('<ul>').append(leftElems.clone(true)));
var rightElems = li.slice(left, amount);
rightElems.replaceWith($('<ul>').append(rightElems.clone(true)));
You could also generalize these last two parts: http://jsfiddle.net/TBhYX/1/ .
var li = $('li'),
amount = li.length,
left = amount / 2 | 0,
right = amount - left;
$.each([ [ 0, left],
[left, amount] ], function(i, v) {
var elems = li.slice.apply(li, v);
elems.replaceWith(
$('<ul>').append(elems.clone(true))
);
});
First you can use .each from jQuery and count them...
http://api.jquery.com/jQuery.each/
Then create the 2 ul, and then take only half of them and put them in the first ul. and then in the second...
Example code:
<div class="take_those">
<li>One</li>
<li>Ein</li>
</div>
<ul class="first">
</ul>
<ul class="second">
</ul>
See what the elements are like
$(document).ready(function() {
var total_items = 0;
total_items = $(".take_those li").length;
$(".take_those li").each(function(i) {
if(i<(total_items/2)) {
$(".first").append("<li>"+$(this).html()+"</li>");
} else {
$(".second").append("<li>"+$(this).html()+"</li>");
}
});
});
Or something like that...
Did this help you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.