jQuery Selectors

A jQuery Selector is a function that is used to select and manipulate one or more HTML elements based on their ID, classes, attributes, types, etc.

The jQuery selectors can be easily identified by a dollar sign and parentheses e.g. $() at the start of the selector.

Some of the jQuery selectors are listed below:

SELECTORS SYNTAX DESCRIPTION
* $(“*”) Selects all elements
#id $(“#firstname”) Select the element with id=”firstname”
.class $(“.primary”) Select all elements with class=”primary”
element $(this) Select the current HTML element
:first $(“p:first”) Select the first <p> element
:first $(“ul li:first”) Selects the first <li> element of the first <ul>
:first-child $(“ul li:first-child”) Selects the first <li> element of every <ul>
[attribute] $(“[href]”) Selects all elements with an href attribute
[attribute=value] $(“a[target=’_blank’]”) Selects all <a> elements with a target attribute value equal to “_blank”
[attribute!=value] $(“a[target!=’_blank’]”) Selects all <a> elements with a target attribute value NOT equal to “_blank”
:button $(“:button”) Selects all <button> elements and <input> elements of type=”button”
:even $(“tr:even”) Selects all even <tr> elements
:odd $(“tr:odd”) Select all odd <tr> elements

 

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>Example of jQuery Selectors</h2>
<p>The do while loop repeatedly executes a block of statements until a particular condition is true. It first executes a block of statements and then check the condition.</p>
<button>Click me to hide paragraphs</button>
</body>
</html>