J

JavaScript Handbook

Clean • Professional

jQuery CSS Methods in JavaScript

1 minute

jQuery CSS Methods

jQuery provides methods to read, set, and manipulate CSS styles dynamically.

You can directly apply inline styles or toggle CSS classes for cleaner design control.

css() – Get or Set CSS Properties

  • Get: Returns the value of a CSS property.
  • Set: Adds or changes CSS styles dynamically.
// Get color
let color = $("p").css("color");

// Set single property
$("p").css("color", "blue");

// Set multiple properties
$("p").css({
  "color": "white",
  "background-color": "black",
  "font-size": "18px"
});

addClass() – Add CSS Class

Adds one or more CSS classes to selected elements.

$("div").addClass("highlight");

removeClass() – Remove CSS Class

Removes one or more CSS classes from elements.

$("div").removeClass("highlight");

toggleClass() – Toggle Between Classes

Adds the class if not present, or removes it if already applied.

$("button").click(function() {
  $("p").toggleClass("active");
});

hasClass() – Check If Element Has a Class

Checks whether a particular class exists on an element.

if ($("p").hasClass("active")) {
  alert("Paragraph is active!");
}

Example: CSS Methods

<!DOCTYPE html>
<html>
<head>
  <title>jQuery CSS Methods Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    .highlight {
      background-color: yellow;
      color: red;
    }
  </style>
</head>
<body>
  <p>This is a paragraph.</p>
  <button id="btn">Toggle Highlight</button>

  <script>
    $(document).ready(function() {
      $("#btn").click(function() {
        $("p").toggleClass("highlight");
        $("p").css("font-size", "20px");
      });
    });
  </script>
</body>
</html>

 

Article 0 of 0