jQuery - Selectors

Basic Selectors

Universal Selector

It selects all the elements available in DOM.

$("*")

This selector selects all HTML elements.

Element Name Selector

It uses element name to find elements. It selects all the elements that has given element name.

$("ul")

This selector selects all unordered list elements.

Class Selector

It uses class attribute to find elements. It selects one or more elements that has given class attribute.

$(".test")

This selector selects all the elements on which class "test" is applied.

Id Selector

It uses id attribute to find elements. It selects one element that has given id attribute.

$("#test")

This selector selects element that has "test" as id attribute.


Hierarchy and Combination Selectors

Hierarchy Selectors are used to select elements on the basis of hierarchical relationship and Combination Selectors are used to select elements by combination of selectors.

Combinations Selectors

We can also use combinations of above selectors to find elements. For Example:

$("ul.test")

It selects all unordered list elements having class name as "test".

$("ul#test")

It selects unordered list elements having value of id attribute as "test".

$("p,ul")

It selects all unordered list elements and all paragraph elements.

$(".test1.test2")

It selects all elements having both classes test1 and test2.

Child Combination Selector (parent > child)

It selects all child elements that are direct children of parent element.

$("div > p")

This selector selects all paragraph elements that are direct children of all div elements.

Descendant Combination Selector (ancestor descendant)

It selects all descendant elements contained within ancestor elements.

$("div p")

This selector selects all paragraph elements that are inside of all div elements whether they are direct children or not.

prev + next Selector

It selects all immediate next elements that are next to a prev element.

$("div + p")

This selector selects all paragraph elements that are placed immediately after div elements.

prev ~ siblings Selector

It selects all sibling elements that comes after prev elements and match the siblings selector.

$("div ~ p")

This selector selects all paragraph elements that are siblings of div elements.