简体   繁体   中英

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

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM