简体   繁体   中英

Wrapping multiple images inside a <div> in jQuery

I need to find all the images inside a 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.

很难说,因为我看不到您的标记,但类似:

$('.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)'));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM