I want to use JCarousel to display UL elements with LI containing only eight images (two rows of four), something that looks like this:
<li>
<div>
[image][image][image][image]
[image][image][image][image]</div>
</li>
<li>
<div>
[image][image][image][image]
[image][image][image][image]</div>
</li>
I thought a good way to do this would be to use after()
to add some closing and opening tags like so:
$(".jcarousel-item img:nth-child(9)").after(</div></li><li><div>);
But I guess I am misunderstanding the nature of after()
, because it won't seem to insert closing tags unless they lead with opening tags.
Is there a better way to do this with wrapInner()
?
So you're starting with a single ul
with a single li
with a div
containing a whole bunch of images & you want to split it into a set of li
s, each containing 8 images right? If so, this will work:
var images = $("img");
while (images.length > 8) {
images.slice(8, 16).appendTo("ul").wrapAll("<li><div></div></li>");
images = images.slice(16);
}
Basically it slices off 8 image chunks from the collection of images and appends them back into the ul
in their own li
s (it leaves the original li
with the 1st 8 images). Obviously, you'd need to adjust your selectors as presumably you've got other images and unordered lists on your page.
Edit: to explain the reason why .after
is not working the way you were expecting it to - I believe jQuery tries to manipulate the DOM rather than the raw HTML. So you can't just append random chunks of HTML unless they can be parsed and turned into actual DOM nodes. In other words the content you pass to .after
effectively needs to be a valid and complete piece of HTML in its own right. So, because jQuery can't work out how to turn something like "</div></li><li><div>
" into a node, it acts a bit strangely (I'm guessing in this case it ignores the two initial close tags, since they don't make sense on their own & then create's the li
& div
nodes & then effectively auto-closes them for you).