|Just jQuery The Core UI - Selectors|
|Written by Ian Elliot|
|Friday, 27 May 2022|
Page 2 of 2
Combining Type Selectors
Now that we know that the basic selector is just the type selector it is time to discover how they can be used in combination.
If you have two type selectors T1 and T2 then just writing them one after the other:
Putting this another way, all T2s that are children of a T1. For example:
selects all <p> elements that are contained within a <div>. Notice that it doesn't matter how deeply nested the <p> is within other elements. If there is a containing <div> then the <p> is selected.
You can use as many types as you like to define complicated nestings of elements. For example:
$("div div p")
selects <p> elements that are nested within two divs. Notice that this means at least two divs – it doesn't select <p> elements nested within one div but it does select <p> elements nested withing two, three or more <divs>.
You can use the universal selector to define nesting relationships that are independent of type. For example:
$("div * p")
means <p> elements nested within any other element and an outer containing div.
If you simply write type selectors separated by spaces then you are defining nesting relationships. The separators > and + indicate two other types of relationship:
So, for example: $("div > p")
selects all <p> elements that are immediately contained within a div. Compare this to:
which means that the p has to be contained within the div, but there can be other types between it and the div.
$("h1 + div")
selects all divs that immediately follow a h1.
The final way to combine type selectors is very simple. You can making a list of selectors separated by commas to mean elements that match any of the selectors. For example:
$("h1, div, p")
selects all h1, div and p elements
As you might expect, you can mix these types of selectors together. It may be obvious that you can do it, but sometimes it can be very difficult to work out what they mean.
$("div * p > span ")
specifies a <span> that is immediately contained by a <p>, contained by any element contained by a <div>.
The trick in understanding more complicated selectors is to realize that you read them from right to left with the conditions being added to reduce the number of elements selected.
So starting from the right we have span, i.e. pick out elements that correspond to <span>. Next we have p> which adds the condition that the span has to be a child of a <p>, which according to the * has to be a child of some other element and finally the div adds the condition that it has to be contained by a <div>.
If you read the selector from right to left adding conditions as you go you should find it easy to understand the most complex selectors possible.
In book but not in this extract
Available as a Book:
buy from Amazon
buy from Amazon
or email your comment to: firstname.lastname@example.org
|Last Updated ( Friday, 27 May 2022 )|