Selecting Elements In jQuery
The default way of selecting an element in jQuery is as follows:
jQuery('p')
This selects all the elements on the page, to do with as you please. If some paragraphs have a class of “emphasis”, you can select those with the filter() method like so:
jQuery('p').filter('emphasis')
I can’t tell yet whether the filter() method only works with classes or whether it works on other things too.
Moving on, we now have the find() method. Think of paragraphs with bolded text in them. If we want to select just the bolded items, we could use:
jQuery('p').find('strong')
Note that find() is used to find descendant elements. The <strong> elements are within the <p> elements, so they are descendants. But get this: you can use CSS selector notation! If you were to style the bolded elements above using CSS, you might create the following rule in your stylesheet:
p strong {
color: #c00;
}
Well, you can use that CSS notation to select those elements in jQuery, like so:
jQuery('p strong')
So, to recap, we use these methods have the following uses:
- jQuery(‘p’).filter(‘.emphasis’) – selects paragraphs with a class of “emphasis”
- jQuery(‘p’).find(‘strong’) – finds bolded elements within paragraphs
- jQuery(‘p strong’) – another way of selecting bolded elements within paragraphs, the CSS way!
Estupendo! The more I learn about jQuery, the more I like it. OK, this is day 1, so I’ll reserve judgement for at least another couple of days.