• jQuery Video Tutorials

jQuery multiple elements Selector



The multiple elements selector in jQuery allows you to select multiple HTML elements using a single jQuery selector. To do so, we need to seperate each element with a (,) comma.

Syntax

Following is the syntax to define multiple elements in jQuery −

$("element1,element2,element3,...")

Parameters

The "element1,element2,element3,..." specifies the elements to be selected.

Example 1

In the following example, we are selecting all <p> and <div> elements using the element selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
        $("p, div").css("background-color", "yellow");
    })
  });
</script>
</head>
<body>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <button>Click</button>
</body>
</html>

When we click the button, all the <p> and <div> elements will be selected and highlighted with yellow color background.

Example 2

In this example, we are selecting all the <p>, <div> and <h3> and hides them when the button is clicked −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
        $("p, div, h3").hide();
    })
  });
</script>
</head>
<body>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <button>Click</button>
</body>
</html>

After clicking the button, all the selected elements (<p>, <div> and <h3>) will be hidden from the DOM.

Example 3

Here, we are using the "*" selector to select all the elements in the DOM −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
        $("*").hide();
    })
  });
</script>
</head>
<body>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <p>Paragraph element.</p>
  <div>Div element.</div>
  <h3>Heading element.</h3>
  <button>Click</button>
</body>
</html>

After clicking the button, all the selected elements in the DOM will be hidden.

jquery_ref_selectors.htm
Advertisements