2

I am trying to select an image by the CSS that is automatically applied through a CMS to that image and then add a class. Here is my script:

$(document).ready(function() {
    if ($('.pageBody p img').css('float') === 'right') {
        $('.pageBody p img').addClass('float-right');
    }
});

That script works just fine with an image that has float: right applied. There is another image that has float: left applied. The problem is, if I switch "right" to "left" in the script than it wont' work. For example, if I have an image set to float: left and use this script than it doesn't work:

$(document).ready(function() {
    if ($('.pageBody p img').css('float') === 'left') {
        $('.pageBody p img').addClass('float-left');
    }
});
3
  • If it works with right, and not left, are you sure it actually has that style applied. Commented Feb 13, 2013 at 15:36
  • Is the other image inside a tag with the pageBody class wrapped inside a p tag? Commented Feb 13, 2013 at 15:37
  • Can you print out the CSS value by doing something like console.log($('.pageBody p img').css('float')), it should give you enough information. Commented Feb 13, 2013 at 15:37

1 Answer 1

5

Your current code will only work if the image you're interested in is the first one in the document. You can use filter() to locate that image regardless of its position in the DOM:

$(document).ready(function() {
    $(".pageBody p img").filter(function() {
        return $(this).css("float") == "left";
    }).addClass("float-left");
});

Alternatively, you can use the form of addClass() that takes a function to add float-left or float-right classes to all the images depending on the value of their float style:

$(document).ready(function() {
    $(".pageBody p img").addClass(function() {
        var direction = $(this).css("float");
        if (direction == "left" || direction == "right") {
            return "float-" + direction;
        } else {
            return "";
        }
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant. Thanks for the help. I can't accept your answer for seven minutes but as soon as I can I will.
or wack it with each: return ($(this).css("float") == "left" || $(this).css("float") == "right"); }).each(function () { $(this).addClass("float-" + $(this).css("float")); }); nice answer btw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.