jQuery Selectors

In this tutorial you will learn how to select HTML elements using jQuery.

Selecting Elements with jQuery

JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But, before you can perform any action you need to find or select the target HTML element. So we are here using jQuery Selectors.

Selecting the elements through a typical JavaScript approach could be very painful, but the jQuery Selectors works like a magic here. The ability of making the DOM elements selection simple and easy is one of the most powerful feature of the jQuery.

Tip:The jQuery supports almost all the selectors defined in the latest CSS3 specifications, as well as it has its own custom selectors. These custom selectors greatly enhance the capabilities selecting the HTML elements on a page.

In the following sections, you will see some of the common ways of selecting the elements on a page and do something with them using the jQuery Selectors.

Selecting Elements by ID

You can use the ID selector to select a single element with the unique ID on the page.

For example, the following jQuery code will select and highlight an element having the ID attribute id="mark", when the document is ready to be manipulated.

In the example above, the $(document).ready() is an event that is used to manipulate a page safely with the jQuery. Code included inside this event will only run once the page DOM is ready. We’ll learn more about the events in next chapter.


Selecting Elements by Class Name

The class selector can be used to select the elements with a specific class.

For example, the following jQuery code will select and highlight the elements having the class attribute class="mark", when the document is ready.

Selecting Elements by Name

The element selector can be used to select elements based on the element name.

For example, the following jQuery code will select and highlight all the paragraph i.e. the <p> elements of the document when it is ready.

Selecting Elements by Attribute

You can use the attribute selector to select an element by one of its HTML attributes, such as a link’s target attribute or an input’s type attribute, etc.

For example, the following jQuery code will select and highlight all the text inputs i.e.<input> elements with the type="text", when the document is ready.

Selecting Elements by Compound CSS Selector

You can also combine the CSS selectors to make your selection even more precise.

For instance, you can combine the class selector with an element selector to find the elements in a document that has certain type and class.

jQuery Custom Selector

In addition to the CSS defined selectors, jQuery provides its own custom selector to further enhancing the capabilities of selecting elements on a page.

This is the end of Tutorial to use jQuery Selectors. If you have any question, ask it at our Forum Section.