jQuery Selectors
jQuery selectors are a key part of the jQuery library.
jQuery Selectors
jQuery selectors let you choose and change HTML elements.
jQuery selectors help to locate HTML elements by their name, id, classes, types, attributes, attribute values, and more. They are similar to CSS Selectors and also have some unique custom selectors.
In jQuery, all selectors begin with $() symbols.
The element Selector
The jQuery element selector picks elements by their tag name.
You can select all <p> elements on a page like this:
$("p")
Example
When a user clicks the button, all <p> elements will be hidden:
The #id Selector
The jQuery #id selector finds an HTML element by its id attribute.
An id must be unique on a page, so use the #id selector to find one specific element.
To locate an element with a particular id, use a hash symbol followed by the id of the HTML element:
$("#test")
Example
When someone clicks on a button, the element with the id "test" will disappear.
The .class Selector
The jQuery selector .class locates elements that have a particular class.
To locate elements with a particular class, type a dot (.) and then the class name after it:
$(".test")
Example
When a user presses a button, the elements with class="test" will disappear.
More Examples of jQuery Selectors
| Syntax | Description |
|---|---|
| $("*") | Selects all elements |
| $(this) | Selects the current HTML element |
| $("p.intro") | Selects all <p> elements with class="intro" |
| $("p:first") | Selects the first <p> element |
| $("ul li:first") | Selects the first <li> element of the first <ul> |
| $("ul li:first-child") | Selects the first <li> element of every <ul> |
| $("[href]") | Selects all elements with an href attribute |
| $("a[target='_blank']") | Selects all <a> elements with a target attribute value equal to "_blank" |
| $("a[target!='_blank']") | Selects all <a> elements with a target attribute value NOT equal to "_blank" |
| $(":button") | Selects all <button> elements and <input> elements of type="button" |
| $("tr:even") | Selects all even <tr> elements |
| $("tr:odd") | Selects all odd <tr> elements |
Functions In a Separate File
If your website has many pages and you want your jQuery functions to be easy to maintain, you can place them in a separate .js file.
In this tutorial, when we show jQuery, the functions are placed directly in the <head> section. However, sometimes it's better to put them in a separate file, like this (use the src attribute to refer to the .js file):
Example
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>
CSS
Jquery