Using ID and Class Selectors in jQuery
Element Selector
The element selector targets HTML elements based on their tag name.
$("p")
This selects all <p> elements on the page.
ID Selector
The ID selector targets an element with a specific ID attribute.
$("#myElement")
This selects the element with id="myElement"
.
Class Selector
The class selector targets elements with a specific class attribute.
$(".myClass")
This selects all elements with class="myClass"
.
All in one Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
alert("Welcome to jquery");
$("button").click(function(){
alert("You Clicked the button");
});
$("#btn1").click(function(){
alert("You Clicked the ID button");
});
$(".btn2").click(function(){
alert("You Clicked the Class button");
});
});
</script>
</head>
<body>
<button>Normal Button</button>
<button id="btn1">ID Button</button>
<button class="btn2">Class Button</button>
</body>
</html>
Run Code