This tutorial aims to introduce how to master jQuery selectors, a fundamental aspect of manipulating HTML documents with jQuery. By the end of this tutorial, you will be able to select elements by their ID, class, and element type.
Prerequisites: Fundamental knowledge of HTML, CSS, and JavaScript is necessary. Prior exposure to jQuery is beneficial but not a hard requirement.
jQuery selectors are the way we can select and manipulate HTML elements. They are based on the existing CSS Selectors, and in addition, they have some custom selectors. Here's a detailed explanation of the primary selectors:
Here are some code examples demonstrating jQuery selectors:
$("p").css("background-color", "yellow");
This code selects all <p>
elements and changes their background color to yellow.
$("#test").css("background-color", "yellow");
This code selects the HTML element with id="test" and changes its background color to yellow.
$(".test").css("background-color", "yellow");
This code selects all elements with class="test" and changes their background color to yellow.
In this tutorial, we have covered how to select elements using jQuery by their type, ID, and class. These selectors form the basis of jQuery's power, allowing developers to easily find and manipulate HTML elements. Next, you could learn about jQuery events, another crucial aspect of jQuery.
Here are some exercises to help you practice:
<div>
elements with a class of "container" and change their border to 1px solid black. Solution:
$(".container").css("border", "1px solid black");
Solution:
$("#special").css("font-size", "24px");
<p>
elements inside a <div>
and change their color to red.Solution:
$("div p").css("color", "red");
For further practice, try manipulating different CSS properties of various elements using jQuery selectors.