174

I am trying to change the CSS using jQuery:

$(init);
    
function init() {
    $("h1").css("backgroundColor", "yellow");
    $("#myParagraph").css({"backgroundColor":"black","color":"white");
    $(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
    <h1>Header</h1>
    <p id="myParagraph">This is some paragraph text</p>
</div>

What am I missing here?

miken32
  • 42,008
  • 16
  • 111
  • 154
user449914
  • 1,821
  • 2
  • 12
  • 11
  • 2
    it's been fixed. As replied below, there are two solutions: (1) remove the curly brace and change backgroundColor to background-color (css class) or - the core problem) put the missing curly brase at the end and use the DOM/JS notation witch also works. THANKS EVERYONE! – user449914 Sep 16 '10 at 19:41
  • 1
    manipulating CSS in javascript can be considered poor practice. Consider add/remove/toggling classes. – Austin Aug 05 '15 at 18:06

11 Answers11

254

Ignore the people that are suggesting that the property name is the issue. The jQuery API documentation explicitly states that either notation is acceptable: http://api.jquery.com/css/

The actual problem is that you are missing a closing curly brace on this line:

$("#myParagraph").css({"backgroundColor":"black","color":"white");

Change it to this:

$("#myParagraph").css({"backgroundColor": "black", "color": "white"});

Here's a working demo: http://jsfiddle.net/YPYz8/

$(init);
    
function init() {
    $("h1").css("backgroundColor", "yellow");
    $("#myParagraph").css({ "backgroundColor": "black", "color": "white" });
    $(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
    <h1>Header</h1>
    <p id="myParagraph">This is some paragraph text</p>
</div>
Unsenzrd
  • 78
  • 1
  • 10
Ender
  • 14,995
  • 8
  • 36
  • 51
  • How do you add a value as a variable, for example `paddingTop` as *x* number of px? Every kind of syntax I've tried has resulted in an error. – Mentalist Apr 22 '19 at 04:30
  • Never mind. Got it: `$("#main").css({paddingTop: (var_name+20) + "px"});` – Mentalist Apr 22 '19 at 05:26
  • @Ender: using `css()` all the css is reset and only the css mentioned in this function persists. How can I only add css which is to be changed and retain previous css ? – SimpleGuy Sep 02 '20 at 05:46
67

You can do either:

$("h1").css("background-color", "yellow");

Or:

$("h1").css({backgroundColor: "yellow"});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • 3
    `{"backgroundColor": "yellow"}` is valid, though superfluous. – Tgr Sep 16 '10 at 19:37
  • @user449914: you don't need to put quotes around the property names in an object literal - `{foo: "bar"}` is the same as `{"foo": "bar"}`. – Tgr Sep 16 '10 at 19:44
25

To clear things up a little, since some of the answers are providing incorrect information:


The jQuery .css() method allows the use of either DOM or CSS notation in many cases. So, both backgroundColor and background-color will get the job done.

Additionally, when you call .css() with arguments you have two choices as to what the arguments can be. They can either be 2 comma separated strings representing a css property and its value, or it can be a Javascript object containing one or more key value pairs of CSS properties and values.

In conclusion the only thing wrong with your code is a missing }. The line should read:

$("#myParagraph").css({"backgroundColor":"black","color":"white"});

You cannot leave the curly brackets out, but you may leave the quotes out from around backgroundColor and color. If you use background-color you must put quotes around it because of the hyphen.

In general, it's a good habit to quote your Javascript objects, since problems can arise if you do not quote an existing keyword.


A final note is that about the jQuery .ready() method

$(handler);

is synonymous with:

$(document).ready(handler);

as well as with a third not recommended form.

This means that $(init) is completely correct, since init is the handler in that instance. So, init will be fired when the DOM is constructed.

Community
  • 1
  • 1
Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
11

The .css() method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.

In its simplest form, the .css() method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.

$('.example').css('background-color', 'red');

This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.

But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.

Instead, you can pass the .css() method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.

$('.example').css({
    'background-color': 'red',
    'border' : '1px solid red',
    'color' : 'white',
    'font-size': '32px',
    'text-align' : 'center',
    'display' : 'inline-block'
});

This will change all of these CSS properties on the ‘.example’ elements.

Johnny
  • 14,397
  • 15
  • 77
  • 118
10

When you are using Multiple css property with jQuery then you must use the curly Brace in starting and in the end. You are missing the ending curly brace.

function init() {
 $("h1").css("backgroundColor", "yellow");

 $("#myParagraph").css({"background-color":"black","color":"white"});

 $(".bordered").css("border", "1px solid black");
}

You can have a look at this jQuery CSS Selector tutorial.

Sadi
  • 366
  • 3
  • 6
5
 If you have one css:

   $("p").css("background-color": "pink");

If you have more than one css: 

  $("p").css({"background-color": "pink", "font-size": "200%"});

Or you can use:

var style ="background-color:red;";
$("p").attr("style", style);
Sarasjd
  • 199
  • 2
  • 11
3

Just wanted to add that when using numbers for values with the css method you have to add them outside the apostrophe and then add the CSS unit in apostrophes.

$('.block').css('width',50 + '%');

or

var $block = $('.block')    

$block.css({ 'width': 50 + '%', 'height': 4 + 'em', 'background': '#FFDAB9' });
Karan
  • 12,059
  • 3
  • 24
  • 40
lowtechsun
  • 1,915
  • 5
  • 27
  • 55
1
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $( document ).ready(function() {
         $('h1').css('color','#3498db');
      });
    </script>
    <style>
      .wrapper{
        height:450px;
        background:#ededed;
        text-align:center
      }
    </style>
  </head>
  <body>
    <div class="wrapper">
      <h1>Title</h1>
    </div>
  </body>
</html>
Nikit Barochiya
  • 971
  • 11
  • 14
1

$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});

1

$(function(){ 
$('.bordered').css({
"border":"1px solid #EFEFEF",
"margin":"0 auto",
"width":"80%"
});

$('h1').css({
"margin-left":"10px"
});

$('#myParagraph').css({
"margin-left":"10px",
"font-family":"sans-serif"
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
<h1>Header</h1>
<p id="myParagraph">This is some paragraph text</p>
</div>
  • While this code may answer the question, providing information on how and why it solves the problem improves its long-term value. – L_J Aug 14 '18 at 09:11
0

wrong code:$("#myParagraph").css({"backgroundColor":"black","color":"white");

its missing "}" after white"

change it to this

 $("#myParagraph").css({"background-color":"black","color":"white"});
galexy
  • 343
  • 3
  • 16
  • 37