JavaScript Code


jQuery – Select elements with any of the tag names


Select elements with any of the given tag names in jQuery

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

Solution

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

var elements = $("tag1, tag2, tag3");

Programs

1. In the following script, when user clicks on the button, we select all the elements in the document whose tag names are in "h2", "h3", 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 tag names
          var elements = $("h2, h3");
    
          // 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>This is second paragraph.</p>
    <p class="my-note">This is third paragraph.</p>
    <h3>Another section</h3>
  </body>
</html>