Welcome to this in-depth tutorial on jQuery Multiple Selectors! In this lesson, we'll explore how to select multiple HTML elements using various techniques in jQuery.
By the end of this tutorial, you'll have a solid understanding of jQuery's multiple selectors and be ready to apply them to your own projects. Let's dive in! š³
Multiple selectors in jQuery allow you to select more than one HTML element at a time, using logical operators such as comma, descendant, child, and sibling selectors. This makes it easy to manipulate multiple elements with a single line of code.
The simplest way to select multiple elements is by separating them with commas.
// Select elements with id "example1" and "example2"
$("example1, example2").css("background-color", "yellow");š” Pro Tip: Use commas to select multiple elements by their id, class, or tag name.
Descendant selectors allow you to select elements that are descendants of a specific parent element.
<div id="parent">
<p>Child 1</p>
<p>Child 2</p>
</div>// Select all paragraphs within the element with id "parent"
$("#parent p").css("background-color", "pink");š” Pro Tip: Use the space character to select elements that are descendants of a specific parent element.
Child selectors allow you to select elements that are immediate children of a specific parent element.
<div id="parent">
<p>Child 1</p>
<ul>
<li>Grandchild 1</li>
<li>Grandchild 2</li>
</ul>
</div>// Select all paragraphs that are immediate children of the element with id "parent"
$("#parent > p").css("background-color", "green");š” Pro Tip: Use the > symbol to select elements that are immediate children of a specific parent element.
Sibling selectors allow you to select elements that share the same parent element.
<div id="parent">
<p>Older sibling</p>
<p>Younger sibling</p>
</div>// Select the younger sibling of the element with id "parent"
$("#parent p:last").css("background-color", "blue");š” Pro Tip: Use the :last or :nth-child(n) selector to select the last or specific sibling element.
Which selector can be used to select all paragraphs that are descendants of a specific parent element?
Now that you understand multiple selectors in jQuery, let's put it all together in a practical example.
<ul id="myList">
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
<li>Date</li>
</ul>
<ul id="myList2">
<li>Mango</li>
<li>Orange</li>
<li>Peach</li>
<li>Guava</li>
</ul>// Change the background color of all li elements with an even index
$("#myList li:even").css("background-color", "lightblue");
// Change the font weight of all li elements in the second list
$("#myList2 li").css("font-weight", "bold");With this knowledge, you're well on your way to mastering jQuery's multiple selectors and enhancing your web development skills. Happy coding! š¤š