jQuery is a lightweight JavaScript library. In the vanilla JavaScript language, the getElementById method is used to select an element. However, jQuery provides a much lighter alternative for the same purpose. The 'jQuery Selector' allows the user to manipulate HTML elements and the data inside it(DOM manipulation).
Syntax
#id Selector: The #id selector specifies an id for an element to be selected. It should not begin with a number and the id attribute must be unique within a document which means it can be used only one time.
Syntax:
html
Output:
html
Output:
html
Output:

$("[attribute=value]")
Here, attribute and value are mandatory.
Some of the most commonly used jQuery selectors
| Syntax | Example | Selection |
|---|---|---|
| * | $("*") | All elements on the webpage |
| #id | $("#geeks") | Elements with id="geeks" | .class | $(".geeks") | All elements with class="geeks" | :first | $("p:first") | First 'p' element of the webpage | :header | $(":header") | All the header elements like h1, h2, h3, h4 etc | :empty | $(":empty") | All the empty elements | :input | $(":input") | All the input elements like text, password etc | :text | $(":text") | Input elements with type="text" | :last-child | $("p:last-child") | Those 'p' elements that are the last child of their parents | :animated | $(":animated") | All the animated elements on the webpage |
$("#example")
The id selector must be used only when the user wants to find a unique element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
How to select elements from
attribute in jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#para").hide();
});
});
</script>
</head>
<body>
<h2>GeeksforGeeks</h2>
<p>This is a constant paragraph.</p>
<p id="para">
This paragraph will get hidden once
the button is clicked.
</p>
<button>Click me</button>
</body>
</html>
- Before Click on the Button:

- After Click on the Button:

$(".example")
Example:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("button").click(function() {
$(".test").hide();
});
});
</script>
</head>
<body>
<h2 class="heading">GeeksForGeeks</h2>
<p class="test">This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
- Before Click on the Button:

- After Click on the Button:

$(":first")
Example:
<!DOCTYPE html>
<html>
<head>
<title>jQuery :first selector</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p:first").css(
"background-color", "green");
});
</script>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p>jQuery</p>
<p>JavaScript</p>
<p>PHP</p>
</body>
</html>
