2

I'm trying to apply unknown styles to unknown selectors and it would seem that shorthand css cannot be applied using jQuery's .css() method. Is this correct? Is there a work-around?

Note that I am building the object dynamically to be passed in to the .css() and do not want to use .css('background','#000') syntax.

$('#example').css({background:'#000000 url("images/bg.gif") repeat-x scroll 0 0 transparent'});

The code above doesn't work. However, the code below does.

$('#example').css({background:'#000'});

And so does this.

$('#example').css({background:'url("images/bg.gif")'});

But when used together they naturally overwrite each other. Any suggestions?

0

2 Answers 2

5
background: #000000 url("images/bg.gif") repeat-x scroll 0 0 transparent;

… is invalid CSS. You've specified the background-color twice (#000000 and transparent). It should work if you use valid CSS.

That said, using classes and external stylesheets is usually a better bet.

Sign up to request clarification or add additional context in comments.

Comments

2

Your better option would be to have a set of pre-defined CSS classes in your CSS file and then apply those target styles on the fly as necessary.

This has the added benefit of keeping your jQuery code down to a readable and manageable level.

So instead of writing:

$('#example').css({background:'url("images/bg.gif")'});

You can opt for the simpler:

$('#example').addClass('myClass1');

1 Comment

I'm trying to apply unknown styles to unknown selectors so this isn't an option but would be the obvious choice.

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.