JavaScript Code


jQuery – Select elements with any of the class names



Select elements with any of the given class names in jQuery

In this tutorial, you will learn how to select all the elements with any of the given class names using jQuery.

Solution

To select the elements in the document that have any of the given class names using jQuery, you can use the multiple class selector, which is created by concatenating class selectors separated by comma.

var elements = $(".my-class-1, .my-class-2, .my-class-3");

Programs

1. In the following script, when user clicks on the button, we select all the elements in the document which has any of the class names [ my-class-1, my-class-2], and change their color to red.

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("#action").click(function() {
          // Select the elements by class names
          var elements = $(".my-class-1, .my-class-2");
    
          // Do something with the selected elements
          elements.css("color", "red");
        });
      });
    </script>
  </head>
  <body>
    <h2>Hello User!</h2>
    <input type="submit" id="action" value="Click Me"></input>
    <p>This is a paragraph.</p>
    <p class="my-class-1">This is second paragraph.</p>
    <p class="my-class-2">This is third paragraph.</p>
    <p class="my-class-7">This is fourth paragraph.</p>
  </body>
</html>


copyright @2023