How to add class if style attribute is present using jQuery

I referenced this page, but I have to do something wrong: jQuery check if an element has a specific attribute

Basically, I want to add the class "img-left" if the image has the attribute style = "float: left" and "img-right" if style = "float: right;" My HTML looks like this:

<img class="content-img" style="float: left;" src="/images/my-img.jpg"> 

And I want it to look like this:

 <img class="content-img img-left" style="float: left;" src="/images/my-img.jpg"> 

Here is what I tried:

 if ($('.content-img').css('float' == 'left')) { $(this).addClass('img-left'); } else { $(this).addClass('img-right'); } 

This results in a JS error, but I can't figure out why. Any help would be greatly appreciated.

Thanks, Vaughn

+4
source share
2 answers

I would suggest simplifying the following:

 $('.content-img').addClass( function(){ var floated = $(this).css('float'); return floated ? 'img-' + floated : ''; }); 

JS Fiddle proof of concept .

This returns the float property and, if set (has a true value), returns the string img- concatenated with the value of the floated variable.

+6
source

That's right, but there is a typo in the if state. It should be like this:

 if ($('.content-img').css('float') == 'left') { $('.content-img').addClass('img-left'); } 
+3
source

All Articles