0

My code thus far:

$(".lorem img:not(.full-img)").each(function() { 
    $(this).addClass("inline-img");
    var imgWidth = $(this).prop('width');
    var imgHeight = $(this).prop('height');
    var imgFloat = $(this).prop('float');

    $(this).wrap('<div class="inline-img-wrap" />'); 
        if ($(this).prop("title")!='') {
            $('<p class="inline-img-caption">').text($(this).prop('title')).insertAfter($(this)); 
        }
});

I am searching for images within a body of text, appending their title values as captions underneath, and wrapping both img and p in a div.inline-img-wrap. That works fine.

What I need help with is applying the styling of the img to the new wrapping div instead. You can see I have created vars for just this, but cannot get applying them to work. $this will always apply to the image, and <div class="inline-img-wrap" style="width:'+imgWidth+'"> doesn't work.

All advice appreciated!

Eamonn
  • 1,338
  • 2
  • 21
  • 53

2 Answers2

1

try using data attribute and css method:

<img data-class='something'  src=''/>;

 $(".lorem img:not(.full-img)").each(function() { 
    $(this).addClass("inline-img");
    var imgWidth = $(this).css('width');
    var imgHeight = $(this).css('height');
    var imgFloat = $(this).css('float');

    $(this).wrap('<div class="inline-img-wrap + " " + $(this).data('class') + " />'); 
        if ($(this).prop("title")!='') {
            $('<p class="inline-img-caption">').text($(this).prop('title')).insertAfter($(this)); 
        }

    $("." + $(this).data('class')).css({"width": imgWidth, `height`: imgHeight, `float`: imgFloat})
});
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Thank you, your's is actually closer to where I was heading myself, but Guard's is working fine for me now :) – Eamonn Jun 30 '12 at 14:51
0

Did I get you right that you need to retrieve the newly created wrapping element?

var $wrap = $(this).wrap('<div class="inline-img-wrap" />').parent();
if ($(this).prop("title")!='') {
    $('<p class="inline-img-caption">').text($(this).prop('title')).appendTo($wrap); 
}
// do any other manipulations with $wrap

P.S. as a side-not: cache your jQuery objects - you are constantly calling $(this) wich is sub-optimal

Guard
  • 6,816
  • 4
  • 38
  • 58
  • My code is in another country from optimal - I'm only beginning, so it only visits optimal on holidays :) Let me try this out and make sure I understand its mechanics... – Eamonn Jun 30 '12 at 14:44