1

I'm trying to add some style properties on an image but only if it already contains another property. I have more or less figure out how to do this with the following:

if ($('#content p img').css('float') == 'right')
    $('#content p img').css('margin-left', '20px').css('margin-bottom', '20px');

But this obviously changes all images so they have margin left and bottom. How can I do the same but only add the margin to the images that has the float: right; property?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
just_user
  • 11,769
  • 19
  • 90
  • 135

2 Answers2

5

Use filter:

$('#content p img').filter(function() {
    return this.style.float === "right";
}).css('margin-left', '20px').css('margin-bottom', '20px');

And you can call css just once if you like, passing in a set of changes to make:

$('#content p img').filter(function() {
    return this.style.float === "right";
}).css({
    'margin-left':   '20px',
    'margin-bottom': '20px'
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

Try:

$('#content p img').each(function(){
    if($(this).css('float') == 'right') 
        $(this).css('margin-left', '20px').css('margin-bottom', '20px');
})
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57