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.