Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class if style attribute is present using Jquery

Tags:

jquery

css

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

like image 200
Vaughn D. Taylor Avatar asked Dec 27 '22 19:12

Vaughn D. Taylor


2 Answers

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.

like image 167
David Thomas Avatar answered Dec 29 '22 09:12

David Thomas


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');
}
like image 33
McGarnagle Avatar answered Dec 29 '22 10:12

McGarnagle