Selectors in JQuery is used to select specific document objects like <body>, <h1>, <p>, <a> and many more. It’s use has made writing JQuery very easier and get the required DOM to have control over it.
Using Basic CSS Selectors
Any DOM element may have their unique ID or group of selctors may have a common class for styling. The ID selects unique element from the HTML DOM and class is applied for a wide selection. For eg.
<p id="myParagraph">This is the paragraph with ID attribute.<p><p class="ourParagraph">This is first the paragraph with Class attribute.</p><p class="ourParagraph">This is second paragraph with Class attribute.</p>
The p#myParagraph selects the paragraph with ID of myParagraph and p.myParagraph slects all the paragraph with class of ourParagraph.Each id value must be used only once within a document. If more than one element has been assigned the same id, queries that use that id will only select the first matched element in the DOM.
For applying styles to page elements, group of selection methods that work across all
browsers can be applied. Those methods include selection by an element’s ID, CSS class name,
tag name, and the DOM hierarchy of the page elements.
Here are some examples to give you a quick refresher.
- a – This selector matches all link (<a>) elements.
- #specialID—This selector matches elements that have an id of specialID.
- .specialClass—This selector matches elements that have the class of specialClass.
- a#specialID.specialClass—This selector matches links with an id of specialID
and a class of specialClass.
These basic selectors are powerful, but sometimes we need even finer-grained
control over which elements we want to match. jQuery meets this challenge and
steps up to the plate with even more advanced selectors.