How do I wrap a repeatbale set of elements in jQuery?
In jQuery how would I go about wrapping a repeatable set of elements with a div?
For example I have:
img
h4
p
img
h4
p
img
h4
p
开发者_如何学JAVA
I need to wrap each img
, h4
, p
set with a div class="container"
. So it will look like:
<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>
<div class="container"> img h4 p </div>
I keep getting nested div.containers
!
You can do something like this:
var elems = $("#content").find("img, h4, p");
for(var i = 0; i < elems.length; i+=3) {
elems.slice(i, i+3).wrapAll("<div class='container'></div>");
}
This works by selecting the container these elements are in and grabbing this specific types, if the elements you want are everything, you can replace .find(selector)
with .children()
, in this case I used this for the parent element:
<div id="container"></div>
You can see a working demo here
Your example is pretty simple, so this will work:
$("h4").each(function () {
$(this).prev().andSelf().next().andSelf().wrapAll("<div class='container'/>");
});
demo here
精彩评论