How to add css using jquery

Learn how to add css style using jquery.

Jquery css method set’s or get the style to the specified elements.

Syntax

//Get
$(element).css("propertyName"); 

//Set
$(element).css("propertyName", "value");

Getting property value

We can use the css method to get one or more property values.

Single value

<div class="learnersbucket"></div>
<style>
.learnersbucket{
  height: 300px;
  width: 500px;
  color: red;
}
</style>

let value = $('.learnersbucket').css('color');
console.log(value);
//"rgb(255, 0, 0)"

Multiple values

We can pass the array of properties whose value we want to get. It returns the list of object with property & value pair.

<div class="learnersbucket"></div>
<style>
.learnersbucket{
  height: 300px;
  width: 500px;
  color: red;
}
</style>

let value = $('.learnersbucket').css(['height', 'width', 'color']);
console.log(value);

/*
Object {
  color: "rgb(255, 0, 0)",
  height: "300px",
  width: "500px"
}
*/

Setting property value

Adding single style

$('.learnersbucket').css('color', 'red');

Adding single style with callback function

We can also use the callback function to set the style of the elements. The callback function has two parameters position of the element(zero based like array) and previousValue.

$('.learnersbucket').css('height', function(pos, value){
    return 250;
});

let value = $('.learnersbucket').css('height');
console.log(value);
//"250px"

Adding multiple style

We can add multiple style at once by passing them as objects.

$('.learnersbucket').css({"height": "200px", "font-size": "20px", "background": "rgb(0,0,255)"});

Leave a Reply

Your email address will not be published. Required fields are marked *