Exploring jQuery Selectors
 
Published: 07 Apr 2009
Unedited - Community Contributed
Abstract
This article describes the Selectors available in the 1.3.2 version of jQuery. Nihar mentions each selector and filter briefly with an example.
by Nihar Ranjan Nayak
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 41736/ 63

Introduction

Selectors are most important part of the jQuery API or library. They use very easy syntax to identify a set of elements. They completely change the way we work with our JavaScript code. Here i will explain the jQuery Selectors available in the latest version (1.3.2).

So before exploring the Selectors I would recommend to download the latest version of jQuery from jQuery.com. Then create a new web site in Visual Studio. Add the downloaded jQuery.js file to your web site. Then in your Default.aspx page specify the reference to the jQuery.js file like this :

                   <script src="jquery-1.3.2.min.js" type="text/javascript"></script>

At this point you are ready to work with jQuery and to test all the Selectors.

Add a new  <script type="text/javascript"></scripttag. Write all your jQuery code within this tag.

Basic Selectors

#id

To select an element by the ID attribute. If the ID contains special character then you can escape them with backslashes. For example to find a text box with ID txtName you can write the following :

                   $("#txtName")

Then you can do any operation on the text box like getting the value or changing the css class.

element

To find all the elements in the page with the given element name. For example to get all the DIV elements following is the syntax

                    $("div")

This will find all the DIVs present in the page. You can do any operation after that.

.class

To find all elements with the given class name. The following code finds all the elements which have class name 'RedButton'.

                        $(".RedButton")

*

This finds all the elements in the document. The syntax is

                   $("*")

selector 1, selector 2, selector N

This matches the combined result of all the specified selectors. We can specify N number of selectors to get a single result. Suppose you want to find all the DIVs, a text box with ID 'txtName' and a Button with class name 'RedButton'. Then following is the syntax:

                   $("div, #txtName, .RedButton")

Suppose you want to change the border color of all these elements then write :

                   $("div, #txtName, .RedButton").css("border","3px solid blue");

It will change all the specified  elements' border color to blue.

Hierarchy Selectors

ancestor descendant

To find all descendant elements specified by "descendant" of elements specified by "ancestor". This includes all the child and grandchild elements. The following example finds all input elements present inside the element forms.  Any element outside the forms will not be matched.

                   $("form input")

Suppose there is a text box inside a DIV which is inside the forms. Then the DIV as well as the text box will be matched.

parent -> child

To find all child elements specified by "child" of elements specified by "parent". This will find only the immediate child elements not the grand child elements. The following code finds all the DIV inside form element. If there is a text box inside a DIV then that will not be matched. This is the difference between ancestor descendant and parent -> child Selectors.

                   $("form > div")

prev + next

This will find all next elements specified by "next" that are next to elements specified by "prev". Consider the following example :

                   $("label + input").css("color", "red").val("Hello!").

 

This will find all the input elements which are just next to any label element, apply the css properties and set the text to “Hello!”. If there are other input elements but not next to a label then those will not be selected.

 

Matches all sibling elements after the "prev" element that match the filtering "siblings" selector. Example :

                        $("#lblName ~ div")

This code finds only all the DIV elements that are siblings after the element #lblName. If there are any other elements which are siblings after the #lblName then those will not be selected.

Basic Filters

:first

This will find the first selected element. The following code finds the first row in a table of 5 rows.

                   $("tr:first")

:last

Matches the last selected element.

:not(selector)

Filters out all elements matching the given selector. This will select all the elements which doesn't match the given selector. Consider the following example :

                   $("input:not(:checked))

This code will match all the check boxes which are not checked.

:even

Finds all the even elements. The following example find all the even rows i.e. 0Th, 2nd, 4th, 6th and so on.

                   $("tr:even")

:odd

Matches all the odd elements

                        $("tr:odd")

:eq(index)

Finds a single element by its index. The following example finds the 3rd TD in a set of Tds.

                   $("td:eq(3)")

:gt(index)

Finds all the elements which have index more than the given index. The following example finds all the Tds with index greater than 2.

                   $("td:gt(2)")

In a set of 6 TDs only 3rd, 4th, 5th, 6th TDs will be selected.

:lt(index)

Finds all the elements which have index less than the given index.

:header

Matches all Header elements like h1, h2, h3 and so on.

                        $(":header")

:animated

Matches all elements that are currently being animated.

                        $("div:animated")

Suppose there are 3 DIVs out of which one is being animated. Then the above code will select the currently animated DIV.

 

Content Filters

:contains(text)

Finds all elements which contain the given text.

                        $("div:contains('John')")

The above code will find all the DIVs which contains the word 'John'. The argument passed inside contains() is string type and case sensitive.

:empty

Matches all elements that have no children (including text nodes).

                   $("td:empty")

This code will find all the Tds which doesn't have any value or are empty.

:has(selector)

Matches elements which contain at least one element that matches the specified selector.

                        $("div:has(p)")

The above code will match the DIV elements which have a paragraph (p element) inside them. The attribute selector is a selector with which we want to filter by.

:parent

This finds all elements that are parents i.e. they have child elements, including text.

                        $("td:parent")

Finds all tds which have other child control, including text, inside them.

Visibility Filters

:hidden

Finds all hidden elements.

                   $("div:hidden")

The above code will find all the hidden DIVs in the document.

:visible

Finds all visible elements.

                   $("div:visible")

The above code will find all the visible DIVs in the document.

Attribute Filters

[attribute]

Matches elements that have the specified attribute like id, title, name, value etc.

                   $("div[id]")

The above will match all the divs which has a ID.

[attribute=value]

Matches elements that have the specified attribute with a certain value.

                        $("input[class=RedButton]")

The above example will find all the input elements with the class name RedButton. Here attribute is 'class' and value is 'RedButton'.

[attribute!=value]

Matches elements that either don't have the specified attribute or do have the specified attribute but not with a certain value.

                        $("input[class!=RedButton]")

The code will find the input elements which either don't have a class name attribute or have a class name with a value other then 'RedButton'.

[attribute^=value]

Will match elements that have the specified attribute and it starts with a certain value.

                        $("input[id^='txt']")

This code will find all the input elements which have an ID and the ID starts with 'txt'. Other input elements which have an ID but don't start with 'txt' will not be matched.

[attribute$=value]

Matches elements that have the specified attribute and it ends with a certain value.

                   $("input[id$='John']")

This code will find all the input elements which have an ID and the ID ends with 'John'. Other input elements which have an ID but don't start with 'John' will not be matched.

[attribute*=value]

Will match the elements that have the specified attribute and it contains a certain value.

                        $("input[name*='man']")

The code will match all the input elements which have the name attribute and the name attribute contains 'man'.

[attributeFilter1][attributeFilter2][attributeFilterN]

Matches elements that match all of the specified attribute filters.

                        $("input[id][name$='man']")

Finds all inputs that have an id attribute and whose name attribute ends with 'man'.

Child Filters

:nth-child(index/odd/even/equation)

This will match all elements that are the nth-child of their parent or that are the parent's even or odd children. While :eq(index) matches only a single element, this matches more than one: One for each parent with index. Multiple for each parent with even, odd, or equation. The specified index is one-indexed, in contrast to :eq() which starts at zero.

                   $("ul li:nth-child(2)")

:first-child

It will find all the elements that are the first child of their parent. There is a confusion between :first and :first-child. While :first matches only a single element :first-child matches all the first elements, one for each parent.

                   $("div input:first-child")

This finds the first input elements in each matched div element. Suppose there are 3 text boxes in each div. Then the first text box of each div will be selected. That means in total 3 text boxes will be selected or matched.

:last-child

It will find all the elements that are the last child of their parent. There is a confusion between :last and :last-child. While :last matches only a single element :last-child matches all the last elements, one for each parent.

                   $("div input:last-child")

This finds the last input elements in each matched div element. Suppose there are 3 text boxes in each div. Then the last text box of each div will be selected. That means in total 3 text boxes will be selected or matched.

:only-child

This finds all the elements which are only child of their parent. If their parent has more than one elements inside them then none will be matched.

                   $("div button:only-child")

Suppose there are 3 divs. First div contains no button, Second div contains only one button and the third div contains more than one button. Then the button in the second div will be matched.

Forms Selectors

These type of selectors are used to match elements based on the element name.

:input

This will find all input, buttons, text area and select elements.

                   $(":input")

This finds all the input elements.

:text

This matches all input elemets that are of type text i.e. text boxes. The syntax is like this :

                   $(":text")

This selector is equivalent to $("*:text"). These type of selectors are considered to be slower selectors. So it is recommended to always use $("input:text"). So that first it will match all the input elements and then will match for the text boxes in all the input elements in stead of finding in the whole document.  So this becomes more convinient.

 

:password

This matches all password elements or controls.  The syntax is :

                   $("input:password")

So it finds input controls which are of password type.

:radio

This matches all input elements of type radio.

This selector is equivalent to $("*:radio"). These type of selectors are considered to be slower selectors. So it is recommended to always use $("input:radio"). So that first it will match all the input elements in and then will match for the radio buttons in all the input elements in stead of finding in the whole document.

                   $("input:radio")

:checkbox

This Matches all input elements of type checkbox.

                   $(":checkbox")

This selector is equivalent to $("*:checkbox"). These type of selectors are considered to be slower selectors. So it is recommended to always use $("input:checkbox"). So that first it will match all the input elements in and then will match for the checkboxes in all the input elements in stead of finding in the whole document.

:submit

Matches all input elements of type submit. This is the syntax :

                        $(":submit")

It will not match the button controls which are type button. It only matches the buttons which are type submit.

:image

Matches all input elements of type image. The syntax is

                        $(":image")

:reset

Matches all input elements of type reset. The syntax is :

                   $(":reset")

This will match all the reset type buttons which are generally used to clear out all the elements in the page.

:button

This matches all button elements and input elements of type button.

                   $(":button")

This will find the button controls which are written like <button></button> and the input elements of type button like <input type='button'> as well.

:file

Matches all input elements of type file.

                        $(":file")

This will find all the file type controls used for uploading files in a page.

:hidden

This will find all the hidden elements.

                   $("input:hidden")

The above code will find all the hidden input elements.

Form Filters

:enabled

This will find all the enabled elements in the document.

                        $("input:enabled")

This code will find the enabled input elements not the disabled one.

:disabled

This will find all the disabled elements in the document.

                        $("input:disabled")

This code will find the disabled input elements not the enabled one.

:checked

This will match all the check boxes which are currently checked. The syntax is :

                        $("input:checked")

:selected

This matches the elements or options that are selected in a dropdown or in listbox.

                   $("select option:selected")

This code finds the currently selected options in the dropdown.

Conclusion

Selectors are generally used for selecting or filtering out of elements. We may achieve all the above using  general JavaScript code. But Selectors make it very easy to access DOM elements in a document. So we should make a practice of using jQuery and jQuery Selectors to make life better. In future version of jQuery we may have more new Selectors.
 



User Comments

Title: good   
Name: 00
Date: 2010-01-28 10:44:36 PM
Comment:
thanks
Title: Request   
Name: Pls write more article on JQuery
Date: 2009-05-12 6:46:55 AM
Comment:
Hello Nihar
Please write more articles on JQuery.
Tume lekha ame sahajare khali padhi kam akribu
How is the IDEA?
Excellent Idea...
Title: Ureka   
Name: Lulu
Date: 2009-05-11 10:26:46 AM
Comment:
Really I have been searching this type of article for last 2 months.Thank you Nihar.
Title: Excellent boss   
Name: Sumoon
Date: 2009-05-11 10:23:15 AM
Comment:
Excellent Article boos.Please post tghis type of usefull articles more

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-19 7:53:36 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search