jQuery selector allow us to select and manipulate HTML element(s).
jQuery selectors enable us to “find” DOM element (HTML elements) based on their name, id, classes, type and much more. After selecting an elements we can perform various operation on that element. It is the most powerful feature of the jQuery.
The jQuery selector always start with the dollar sign and parentheses : $().
Let’s see commonly used selector in jQuery.
The element selector
The jQuery element selector used to selects an element based on the element name.
$("p")
Example
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min .js">
</script>
</head>
<body>
<p>This is a paragraph</p>
</body>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("color","blue");
});
});
</script>
</html>
Output:
This is a paragraph
The #id jQuery selector
The jQuery #id selector is used represents a tag with the given id in html to find the specific element.
An id of the html tag should be unique. The id all starting with “#” symbol.
$("#id")
Exmaple
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<p id = "prg">This is a paragraph</p>
</body>
<script>
$(document).ready(function(){
$("#prg").css("color","green");
});
</script>
</html>
Output:
This is a paragraph
The .class jQuery selector
The jQuery .class is used to find elements with a specific class name in the HTML.
$(".class")
Example:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<p class = "newclass">This is a paragraph</p>
</body>
<script>
$(document).ready(function(){
$(".newclass").css("color","orange");
});
</script>
</html>
Output:
This is a paragraph
Selector example
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors. here are some different type of other selector:
ute and
Syntax | description |
$(*) | Used to selects all the elements |
$(this) | Used to selects the current HTML element |
$(“p.intro”) | Used to selects all <p> elements with class=”intro” |
$(“p.first”) | Used to selects the first <p> element |
$(“ul li:first”) | Used to selects the first<li> element of the first <ul> |
$(ul li:first-child) | Used to selects the first <li> elements of every <ul> |
$(“[href]”) | used to selects all the elements with an href attribute |
$(“a[target=’_blank’]”) | Used to select all <a> elements with a target attribute value equal to “_blank” |
$(“a[target!=’_blank’]”) | Used to select all <a> elements with a target attribute value NOT equal to “_blank” |
$(“:button”) | Used to selects all <button> elements and <input> elements of the type =”button” |
$(“tr:even”) | Used to selects all even <tr> elements |
$(“tr:old”) | Used to selects all odd <tr> elements |
Informative content