In this article, I will guide you on JQuery Selectors $().
Jquery selectors play a major role in our development activity like hiding controls, client-side validations, Ajax calls, etc.
What is JQuery?
JQuery is a library built using JavaScript language. It is designed to simplify the client-side scripting of HTML. The main purpose of jQuery is to provide an easy way to use JavaScript on your website to make it more interactive and attractive.
What are JQuery Selectors?
JQuery Selectors are used to select and manipulate HTML elements. With JQuery selectors, you can find or select HTML elements based on their Id, classes, attributes, types, and much more from a DOM.
Syntax
$(document).ready(function(){
$(selector)
});
Element Selector
The elements selector selects the element on the basis of its name.
Syntax
$(document).ready(function(){
$("Html Element Name")
});
Example
Selects all paragraphs 'p' and set the background color to yellow.
<html>
<head>
<title>JQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("p").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>JQuery Element Selector</h1>
<p>This is paragraph one</p>
<p>This is paragraph two.</p>
<p>This is paragraph three.</p>
</body>
</html>
#Id Selector
Id selector selects the element on the basis of its id.
Syntax
$(document).ready(function(){
$("#id of the element")
});
Example
Hide and show paragraphs based on id.
<html>
<head>
<title>JQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#p1").hide();
});
$("#show").click(function(){
$("#p1").show();
});
});
</script>
</head>
<body>
<h1>JQuery #Id Selector</h1>
<div>
<p id="p1"> Hello from parargraph one</p>
<p>Hello from paragraph two </p>
<p>Hello from paragraph three</p>
</div>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
Class Selector
The class selector selects the element on the basis of its class.
Syntax
$(document).ready(function(){
$(".class of the element")
});
Example
Hide and show paragraphs based on class.
<html>
<head>
<title>JQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("#hide").click(function() {
$(".p2").hide();
});
$("#show").click(function() {
$(".p2").show();
});
});
</script>
</head>
<body>
<h1>JQuery Class Selector</h1>
<div>
<p class="p1"> Hello from parargraph one</p>
<p class="p2">Hello from paragraph two </p>
<p class="p3">Hello from paragraph three</p>
</div>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>