jQuery selector is the most significant element in the jQuery library. The main tasks we do in the jQuery are selecting DOM elements and manipulate the elements to carry out the intended actions.
jQuery selector allows us to search and control HTML elements.
We can do this in three ways.
- jQuery select by tag nameSyntax:
$('html_tag_name')This will select all the HTML elements with the tag name. For example $(‘p’) will select all the paragraphs in the DOM. Further reading: jQuery select by name.
- jQuery select by IDSyntax:
$("#ID_of_Element")This will select an element with this id from the DOM. For Example, if there is an element in the DOM like
<div id=’text’>This is text </div>.
We can hide, show, toggle or make any manipulations of the text by selecting the element by its id ‘text’ as $(“#text”). More details are at jQuery select by id.
- jQuery select by class
$(".classname")This will select all elements in the DOM with the specified class name.After the selection of elements, we will have complete control over that component and it could be manipulated in the way we desire to build the web page. Refer more at jQuery select by class.
jQuery selector syntax
All the mentioned selectors can be used alone or combined with other selectors.
jQuery selector example
Let’s look at some common usage of jQuery selector.
- $(“*”): This jQuery selector selects all elements in the HTML document.
- $(this): This selector selects the current HTML element.
- $(“li:not(.myclass)”): This selector selects all <li> elements that do not have class=”myclass”.
- $(“p:first”): This selector selects the first <p> element in the document.
- $(“ul li:first”): This selector selects the first <li> element of the first <ul>
- $(“ul li:first-child”): This selector selects the first <li> element of every <ul>
- $(“[href]”): This jQuery selector selects all elements with an href attribute
- $(“a[target=’_blank’]”): This selector selects all <a> elements with a target attribute value equal to “_blank”
- $(“a[target!=’_blank’]”): This selector selects all <a> elements with a target attribute value NOT equal to “_blank”
- $(“:button”): This selector selects all <button> elements and <input> elements of type=”button”
- $(“tr:even”): This selector selects all even <tr> elements
- $(“tr:odd”): This selector selects all odd <tr> elements
jQuery selectors are a powerful mechanism in the jQuery library. This makes it easier to work with all the elements in the way we want. Using selectors in combination makes it even more powerful and flexible.