I referred to this page, but I must be doing something wrong: jQuery check if element have specific attribute
Basically, I want to add a class of "img-left" if an image has style="float: left" attribute, 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">
This is what I've tried:
if ($('.content-img').css('float' == 'left')) {
$(this).addClass('img-left');
}
else {
$(this).addClass('img-right');
}
This produces a JS error but I cannot sort out why. Any help would be greatly appreciated.
Thanks, Vaughn
I'd suggest simplifying this to the following:
$('.content-img').addClass(
function(){
var floated = $(this).css('float');
return floated ? 'img-' + floated : '';
});
JS Fiddle proof of concept.
This retrieves the float
property and, if it's set (having a truthy value), returns the string img-
concatenated with the value of the floated
variable.
That's right, but there's a typo in the if
condition. Should be like this:
if ($('.content-img').css('float') == 'left') {
$('.content-img').addClass('img-left');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With