jQuery Selectors
jQuery selectors allow you to easily select and manipulate HTML elements. They use the same syntax as CSS selectors, which makes them intuitive and familiar to web developers. Once selected, elements can be modified or used for various operations.
Basic Selectors
Universal Selector (*
)
Selects all elements in the DOM.
$("*").css("background-color", "yellow");
Explanation: The universal selector applies the specified action, such as changing the background color, to all elements on the page.
ID Selector (#id
)
Selects an element with the specified ID.
$("#myId").hide();
Explanation: The ID selector targets the element with the ID myId
and applies the hide()
method to make it invisible.
Class Selector (.class
)
Selects all elements with the specified class.
$(".myClass").css("color", "red");
Explanation: The class selector targets all elements with the class myClass
and changes their text color to red.
Element Selector
Selects all elements of a specific type (e.g., p
, div
).
$("p").text("Updated paragraph content");
Explanation: The element selector targets all <p>
elements and updates their text content to the specified value.
Example: Using Selectors
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Selectors Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Selectors in Action</h1>
<div>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p id="specific">Paragraph 3</p>
</div>
<button id="styleButton">Style Paragraphs</button>
<script>
$(document).ready(function() {
$("#styleButton").click(function() {
$(".text").css("color", "blue");
$("#specific").css("font-weight", "bold");
});
});
</script>
</body>
</html>
Explanation: In this example, multiple jQuery selectors are used. The class selector .text
applies styles to paragraphs with the class text
, while the ID selector #specific
applies a bold font to a specific paragraph. Clicking the button triggers these actions.
Key Takeaways
- Versatile Selectors: jQuery selectors cover a wide range of use cases, from basic to complex element selection.
- Combination: Combine multiple selectors to perform operations on a set of elements.
- CSS-Like Syntax: jQuery selectors follow CSS selector patterns, making them intuitive and easy to use.