How jQuery selects elements using CSS?

jQuery uses CSS selectors to select and manipulate elements on a web page. This powerful feature allows you to target HTML elements using the same syntax you would use in CSS stylesheets. The css(name) method returns a style property value from the first matched element.

CSS Selector Syntax

jQuery follows standard CSS selector patterns to identify elements ?

  • $("element") ? Selects all elements of a specific type
  • $("#id") ? Selects element by ID
  • $(".class") ? Selects elements by class name
  • $("element.class") ? Selects elements with specific class

The css() Method

Here is the description of the parameter used by the css(name) method ?

  • name ? The name of the CSS property to access

Example

You can try to run the following code to learn how jQuery selects elements and retrieves their CSS properties ?

<html>
   <head>
      <title>jQuery CSS Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               var color = $(this).css("background-color");
               $("#result").html("That div is <span style = 'color:" +
                  color + ";'>" + color + "</span>.");
            });
         });
      </script>
       
      <style>
         div { 
            width: 60px; 
            height: 60px; 
            margin: 5px; 
            float: left; 
            cursor: pointer;
         }
      </style>
   </head>
   
   <body>
      <p>Click on any square:</p>
      <span id = "result">&nbsp;</span>
       
      <div style = "background-color:blue;"></div>
      <div style = "background-color:gray;"></div>
      <div style = "background-color:#123456;"></div>
      <div style = "background-color:#f11;"></div>
   </body>
</html>

In this example ?

  • $("div") selects all div elements using CSS element selector
  • $(this) refers to the clicked div element
  • css("background-color") retrieves the background color property
  • $("#result") selects the element with ID "result"

Conclusion

jQuery's CSS selector integration provides a familiar and powerful way to select DOM elements using standard CSS syntax, making it easy to retrieve and manipulate element properties.

Updated on: 2026-03-13T18:49:31+05:30

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements