0

How would I use jQuery to add a <div> around two consecutive elements?

For example, I have an img followed by a span:

<img class="img-responsive" width="850" height="567" title="Title text..." alt="Alt text..." src="image.jpg">
<span class="img-caption">Caption text...</span>

The span contains text which is used as a caption for the image, so I want to wrap both these elements in a <div> so that I can absolutely position the caption to lay over the image.

I've used $( "img" ).before( "<div class='img-container'>" ); to open the div, and $( ".img-caption" ).after( "</div>" ); to close it after the span, but when I look at the page source the div has been opened but then closed automatically and there's no sign of the inserted closing tag after the span. This is what the source looks like:

<div class="img-container"></div>
<img class="img-responsive" width="850" height="567" title="Title text..." alt="Alt text..." src="image.jpg">
<span class="img-caption">Caption text...</span>

What am I doing wrong?

Here's the jQuery function I'm using:

function captionImg() {
    $("img").each(function() {
    $( "img" ).before( "<div class='image-container'>" );
    var imageCaption = $(this).attr("alt");
    if (imageCaption != '') {
        var imgWidth = $(this).width();
        var imgHeight = $(this).height();
        var position = $(this).position();
        var positionTop = (position.top + imgHeight)
        $(".img-caption").remove(); // Remove any existing captions before adding, so multiple copies don't appear on window resize
        $("<span class='img-caption'>"+imageCaption+"</span>")
        .css({"position":"absolute", "bottom":"20px", "left":"36px", "width":imgWidth +"px"})
        .insertAfter(this);
    }
    $( ".img-caption" ).after( "</div>" );          
    });
 }

Any help and advice would be greatly appreciated. Thanks.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
tcarnell
  • 49
  • 2
  • 12
  • 1
    The answer is in your question,"**WRAP**" Use jquery's `wrapAll` function! Just this much should do `$( ".img-responsive,.img-caption" ).wrapAll( "
    " )`
    – Varun Aug 22 '15 at 17:10
  • If you have multiple pairs of image/captions then Varun's method won't work and ends up wrapping all of them in a single div. – j08691 Aug 22 '15 at 17:21
  • Thanks for your help Varun and j08691, but I've chosen to use [CaptionJS](http://captionjs.com/) instead. It does what I need and provides a bit of extra functionality which may prove useful. – tcarnell Aug 23 '15 at 09:49

0 Answers0