I have this list:
<div id="list">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
I want to move each two elements (.item) inside a div with class="parent"
. I tried with the following, but it doesn't work:
var parent = $("<div class='parent'></div>");
$("#list .item:nth-child(1), #list .item:nth-child(2)").appendTo(parent);
$("#list .item:nth-child(3), #list .item:nth-child(4)").appendTo(parent);
$("#list .item:nth-child(5), #list .item:nth-child(6)").appendTo(parent);
parent is a single cached element so each time you use it it will not create a new parent. Not sure if you looking for something like .wrap()? http://api.jquery.com/wrap/ or .wrappAll() http://api.jquery.com/wrapAll/
$('#list').children().wrapAll('<div class="parent"/>');
Store the childrens in an array, then create as many parents as needed and put them back in your list, here is the code:
var list = $("#list"),
items = $.makeArray($(".item"));
list.html("");
for (var i=0; i < items.length; i++) {
if (i%2 == 0) list.appendChild($('<div class="parent"/>'));
$("#list div:last-child").appendChild(items[i]);
}
You can wrap each two child element like this:
var childLists= $('.item');
for(var i = 0, l = childLists.length; i < l; i += 2) {
childLists.slice(i, i+2).wrapAll('<div class="parent"></div>');
}
You can use wrapAll()
method as follows:
$(".item:even").each(function(){ $(this).next().addBack().wrapAll("<div class='parent'></div>"); })
*{ margin:0; padding:0; } body{ background:silver; } .parent{ height:100px; padding:5px; margin:5px; text-align:center; background:dodgerblue; } .item{ height:40px; line-height:40px; margin:5px 0; background:#fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="list"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> <div class="item">5</div> <div class="item">6</div> </div>
you can try this:without wrap you can get it.
<script>
$(document).ready(function(){
var parent = document.createElement("div");
parent.className = "parent";
x = document.getElementById("list");
parent.appendChild(x);
document.body.appendChild(parent);
});
</script>
<div id="list">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
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.