3

I want to change the css of an element using jQuery.

$('p').css({
    padding-left : '6px',
    border-left : '5px solid #555'
});

It does not work.

However, when i use

$('p').css('padding-left','6px');
$('p').css('border-left','5px'); 

it works...

What am I doing wrong here?

Thanks

2
  • 1
    Nothing, attribute names need to be quoted when using .css() Commented Mar 28, 2013 at 14:00
  • By not having the quotes, it is interpreting padding-left as a variable, just wrap them in single quotes and you'll be all set. Commented Mar 28, 2013 at 14:01

5 Answers 5

6

You have to wrap the properties (style attribute) in qoutes ('' or "").

This is because they contain a dash (-).

Working demo

$('p').css({
    'padding-left' : '6px',
    'border-left' : '5px solid #555'
});
Sign up to request clarification or add additional context in comments.

3 Comments

sweet stuff, thank you. you see, I referred to this post: stackoverflow.com/questions/447197/… and there they do not have width and height in quotes''...I guess it is because of the hyphen...
Right. From api.jquery.com/css: "Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. ... Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name."
Correct, if you just wanted to add padding (does not contain a dash) instead of padding-left, you could avoid the qoutes. Some however consider it best practice to always wrap in qoutes. That way you always avoid these kind of situations :)
3

Better to use this way:

CHECK THIS OUT IN FIDDLE HERE

$('p').css({
    paddingLeft : '6px',
    borderLeft : '5px solid #555'
});

in css we use with hyphen - separated all lowercase and enclosed in "" single or double quotes. This way in js/jQuery:

    'padding-left' : '6px',
    'border-left' : '5px solid #555'
//--^-----------^----------------------here 

While in js all the css properties are accessible in camelCase this way:

    paddingLeft : '6px',
    borderLeft : '5px solid #555'
//--^^^^^^^^^^------------------------this way

Comments

2

Because you're not defining them within quotes in the first piece of code.

$('p').css({
    'padding-left' : '6px',
    'border-left' : '5px solid #555'
});

Should work.

Comments

1

Just missing quotes

$('p').css({
    'padding-left' : '6px',
    'border-left' : '5px solid #555'
});

Comments

1

try

$('p').css({
    'padding-left':'6px',
    'border-left':'5px solid #555'
});

Comments

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.