Home »
jQuery
jQuery Selectors
jQuery Selectors: Learn about the jQuery selector, its types, and syntaxes with examples.
Submitted by Pratishtha Saxena, on September 01, 2022
This is one of the most used and most important jQuery functionalities. jQuery selectors help to select the tag or the HTML element that we wish to work on. It just selects the element, and then other actions can be performed on that accordingly.
Syntax:
$('selector');
There are various methods by which we can select the element using selectors.
- By using #id
- By using .class
- By using element
- By using element attribute name
- By using element attribute value, etc.
Similarly, there are other ways of selecting an element using a selector. But we are going to focus on the three major and most used ways – id, class, and element. They are discussed below.
Id Selector
The ID that is passed to an element as an attribute is unique. Using that unique ID, that particular element an be selected. For using ID as selector, we need to pass hash (#) before the id name which indirectly indicates that the element has been selected through its ID attribute.
Syntax:
$('#ID');
Example of jQuery Id Selector
$(document).ready(function () {
$('#myHeading').addClass('heading');
$('#myPara').addClass('para');
$('#myDiv').addClass('box');
});
Class Selectors
jQuery's class attribute can also be used for selecting elements. Here, the class name of the target element has to be passed along with a dot (.) ahead. This dot represents that the element has been selected using its class attribute.
Syntax:
$('#.className');
Example of jQuery Class Selector
$(document).ready(function () {
$('.heading').addClass('heading');
$('.para').addClass('para');
$('.div').addClass('box');
});
Element Selectors
This means that the element is selected using its tag name. This means that if you want to select all the div tags together then instead of passing IDs or class names of them individually, we can pass the element name, i.e., div which will help select them all at once.
Syntax:
$('element');
Example of jQuery Element Selector
$(document).ready(function () {
$('h2 ').addClass('heading');
$('p').addClass('para');
$('div').addClass('box');
});
Similarly other attributes of an element can be used to select them and can work as a selector, but these were the most important selectors.