Wrapping multiple images inside a <div> in jQuery
I need to find all the images inside a开发者_JAVA技巧 div
, and wrap a div
around them. Here's the code I come up with, but that's not working! Why?
jQuery(function() {
my_selection = [];
$('.post').each(function(i) {
if ($(this).find('img').length > 1) {
my_selection.push(['.post:eq(' + i + ')']);
}
});
$(my_selection.join(',')).wrapAll('<div class="wrapper"></div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How about something like:
$('.post img').wrapAll('<div class="wrapper" />');
.post img
will get a collection of IMG
tags within your .post container, and wrapAll
applies the DIV
around each of them.
The manual page for the wrapAll function actually has quite a close example to what you want.
Hard to say because I can't see your markup but something like:
$('.post img').wrapAll('<div class="wrapper" />');
this works!
$('.post').each(function(){
var container = $(this);
$('img', container).wrapAll('<div class="slideshow" />');
});
Try this
$('.post img').each(function() {
$(this).wrap($('<div/>', { 'class': 'wrapper'}));
});
Here is a link to the similar question I asked :
Create new div arround anchor link when clicked
$('img').each(function (){
$(this).wrap('<div class="new" />');
});
Wrap a div around each img inside a .post:
$('.post img').wrap('<div class="wrapper" />');
Wrap a div around each post that has a img:
$('.post:has(img)').wrap('<div class="wrapper" />');
Move all divs that have an img inside a wrapper div:
$('<div class="wrapper" />').append($('.post:has(img)'));
精彩评论