jQuery selectors

I will definitely forget the syntax of jQuery selectors if I do not write jQuery code for some days. So it is better to list them here as a memo.

Select element based on tag:


This is the simplest form of jQuery selector. No special character such as dot and hash needs to be in front of the string of the selector. But the string is limited to a tag name. If there is no tag with that name in current page, the selector selects 0 element.

select based on id:


Putting a hash before an id can select the element with that id.

select based on class:


This will select all elements with classname class.

select based on attribute:


will select all elements with “attribute” attribute regardless of the attribute value. As long as an element has that attribute, it will be selected, even no value is assigned to the attribute.

select based on specific attribute value:


will select elements which have that attribute and the attribute value is “value”.

fuzzy match:


will select elements which have that attribute and the attribute value contains a sub-string “substr”.

Combine multiple selectors:


This combines the tag selector and the attribute selector, which selects only <p> elements AND the elements must have attribute with the attribute value being “value”.


This combines the tag selector and the class selector, which selects the <p> elements that have the classname class.


This combines the class selector and the attribute selector. Only the elements with both the classname class and the “value” attribute are selected. This is equivalent to:


Select based on multiple classes:

$(“.cs1, .cs2″)

will select all elements with either cs1 or cs2(or both). Note that


only selects the elements with both cs1 and cs2. Note also that

$(“.cs1 .cs2″)

only selects .cs2 elements within the children of .cs1 elements. Now you should know the comma, space in the selector expression really matter: comma means grouping, space means descendant. The absence of character between selectors means AND. But you can not write tag immediately after class because if so, the class and the tag can not be separated:


instead, you should write class after tag like


The descendant selector can be replaced by the find method, i.e., the following two have the same effect:

$(“.cs1 .cs2″)


Both select the child elements of .cs1 which have the class .cs2.

In the above examples, there are only two selectors at most in the selector expression. But there can be more than two selectors in the selector expression and the principles we talked apply as well.

Select elements which contain specified text:


will select all <p> which have “text” contained in their text(as a sub-string). The quotes(single quotes or double quotes) around the text do not matter, i.e., the following three get the same result:






Comments are closed, but trackbacks and pingbacks are open.