Selectors: a first introduction
jQuery uses selectors that work like CSS selectors (with a lot of bonus features that we will get to later) The actual library that powers this is called Sizzle http://sizzlejs.com/.
Selecting a DOM element creates a jQuery object. You can call functions on this object to manipulate the DOM elements
Here are the basics. Select a dom element with...
- All the paragraph elements $('p'). Use any element type, span, div,
- Element with id="some-id" : $('#some-id')
- Element with class="some-class" $('.some-class'). Will select elements that have multiple classes if one of them is 'some-class'
- Elements with class"some-class" and/or "another-class"$('.some-class, .another-class')
- Paragraphs with class of "some-class"$('p.some-class')
Some examples
- .item Select all elements with class item (this is id="a1")
- span.item Select all SPAN elements with class item (this is id="a2")
- #different .item Select all elements with class item inside something with id "different" (notice the space!) (this is id="a3")
- #different .item, p.item Select all elements with class item inside something with id "different" AND all paragraphs with class = differen (Notice the comma!) (this is id="a4")
- .item:odd Select every other element with class item (using odd index. :even would select the other ones) (this is id="a5")
spanspanspanspanspanspanspanspanspanspan
This is a div with id="different"
spanspanspanspanspanspanspanspanspanspanparagraph
paragraph
paragraph
paragraph
paragraph
paragraph
paragraph
paragraph
paragraph
paragraph