How to combine a class selector and an attribute selector with jQuery?

A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. We can easily combine a class selector and an attribute selector with jQuery.

To combine selectors, we use the syntax .classname[attribute="value"] where there is no space between the class selector and the attribute selector. This creates a compound selector that matches elements having both the specified class and the specified attribute value.

You can try to run the following code to learn how to combine a class selector and an attribute selector with jQuery ?

Example

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
            $('.myclass[reference="12345"]').css("background-color", "yellow");
         });
      </script>
   </head>
   <body>
      <table>
         <tr class="myclass" reference="12345">
            <td>Row 1 Column 1</td>
         </tr>
         <tr class="myclass" reference="43215">
            <td>Row 2 Column 1</td>
         </tr>
         <tr class="myclass" reference="54321">
            <td>Row 3 Column 1</td>
         </tr>
      </table>
   </body>
</html>

In this example, the jQuery selector $('.myclass[reference="12345"]') targets only the element that has both the class myclass and the attribute reference with the value "12345". As a result, only the first table row will have its background color changed to yellow, while the other rows remain unaffected.

Conclusion

Combining class and attribute selectors in jQuery allows you to precisely target elements that meet multiple criteria, making your DOM manipulation more specific and efficient.

Updated on: 2026-03-13T17:47:04+05:30

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements