Using jQuery , you can easily select HTML elements. But sometimes, when the HTML structure is more complex, refining the elements we choose is a troublesome thing. In this tutorial, we'll explore ten ways to refine and expand the collections we'll be working with.
HTML
First, let's look at the simple page shown below, and through this tutorial we will select the elements.
" Why do we need to further refine a series of elements? Is it because the jQuery selection syntax is not powerful enough? "
Okay, let's start with an example. In the web page mentioned above, when a star is clicked, we need to add class "on" to it and each star on the left . At the same time, we want to change the background color of all star parent elements, so our code is as follows:
On the second line, we get the current object we clicked on. But how to get the parent of stars ? That is div.rating . However, in one page, there are many div.rating . Which one do we want? How to get all the stars to the left of "this" ?
The good news is that jQuery allows us to obtain new collections of elements based on existing collections based on these basic relationships. And these are where traversal functions come into play.
1. children
This function gets the direct children of a set of elements.
This can be very convenient in many situations, take a look at the picture below:
$('.star').click(function(){
$(this).addClass('on');
// How to select the parent element of the current object ?
// How to get all the stars to the left of the current star ?
});