jquery set style property

How to Set Style Property using jQuery

If you want to set a style property for an HTML element using jQuery, you can use the css() method.

Syntax:

$(selector).css(property, value)

The selector parameter selects the element(s) that you want to apply the style to. The property parameter specifies the name of the style property you want to set, and the value parameter specifies the value you want to set it to.

For example, let's say you have a div with an id of "myDiv" that you want to set the background color to red:

<div id="myDiv">Hello World!</div>

You can use the following jQuery code:

$("#myDiv").css("background-color", "red");

This will set the background color of the div to red.

Multiple Style Properties:

If you want to set multiple style properties at once, you can pass an object with property-value pairs as the argument to the css() method.

For example, let's say you want to set both the background color and font size of the div:

$("#myDiv").css({
  "background-color": "red",
  "font-size": "20px"
});

This will set the background color to red and the font size to 20 pixels.

CSS Classes:

If you have a predefined CSS class that you want to apply to an element, you can use the addClass() method.

For example, let's say you have a class called "myClass" defined in your CSS file:

.myClass {
  background-color: red;
  font-size: 20px;
}

You can apply this class to your div using the following jQuery code:

$("#myDiv").addClass("myClass");

This will apply the styles defined in the "myClass" class to your div.

Conclusion:

Setting style properties using jQuery is easy and flexible. You can set a single property or multiple properties, and you can also apply predefined CSS classes to your elements. With jQuery, you have the power to manipulate your HTML and CSS in any way you want.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe