Let us learn JQuery - Part 2 of 9(JQuery Selectors)

Niladri.Biswas
Posted by in jQuery category on for Beginner level | Points: 250 | Views : 11563 red flag
Rating: 5 out of 5  
 3 vote(s)

In this part we will learn about JQuery Selectors


 Download source code for Let us learn JQuery - Part 2 of 9(JQuery Selectors)

Table of Content

  1. Introduction
  2. What is JQuery Selector?
  3. Types of JQuery Selectors
    1. Single Element Name Selectors
    2. Multiple Selectors
    3. Id Selectors
    4. CSS Selectors
    5. Attribute Selectors
    6. Element Visibility Selectors
    7. Form Field Selectors
    8. Parent-Child Selectors
  4. References
  5. Conclusion

Introduction

Our JQuery journey has began with the introduction with the last article JQuery - A formal introduction using "Hello World". In this second part of the entire JQuery journey, we will look into JQuery Selectors, which is the heart of JQuery with lot of examples.

This "Let us learn JQuery" will be a series of article on JQuery.The full series is comprised as under :

  1. JQuery - A formal introduction using "Hello World"
  2. JQuery Selectors
  3. JQuery Traversal
  4. CSS with JQuery
  5. DOM with JQuery
  6. JQuery and Events
  7. Animated effects using JQuery
  8. JQuery and Ajax
  9. Custom JQuery Plugins

What is JQuery Selector?

jQuery selector($),the vital part of JQuery, allow Html elements to be selected and manipulated.It finds the elements by Element Name,Element ID or class and returns a sequence of matched DOM elements upon a successful match. We can they apply methods or logics on those collection for further processing.

Syntax:

$(Selector Expression)

OR

jQuery(Selector Expression)

Types of JQuery Selectors

  1. Single Element Name Selectors
  2. Multiple Selectors
  3. Id Selectors
  4. CSS Selectors
  5. Attribute Selectors
  6. Element Visibility Selectors
  7. Form Field Selectors
  8. Parent-Child Selectors

1.Single Element Name Selectors

Purpose:Selecting all elements of a certain type or kind by their name.

Objective:We want to set the border color of all the table elements to lightgreen and background color of the tables to "yellow"

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("table").css("border", "8px solid #00ff00");
            $("table").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divMain">
	<h2>Single Selector Example</h2>
        <p>
            I am the first Paragraph
            <table>
                    <tr>
                        <td>
                            Col1
                        </td>
                        <td>
                            Col2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            1
                        </td>
                        <td>
                            2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            3
                        </td>
                        <td>
                            4
                        </td>
                    </tr>
                </table>
        </p>
        <p>
            I am the second Paragraph
        </p>
        <p>
            <p>
                I am the fourth Paragraph
                <table>
                    <tr>
                        <td>
                            Col1
                        </td>
                        <td>
                            Col2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            1
                        </td>
                        <td>
                            2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            3
                        </td>
                        <td>
                            4
                        </td>
                    </tr>
                </table>
            </p>
            <p>
                I am the fifth Paragraph
            </p>
            I am the third paragraph
        </p>
    </div>
    </form>
</body>
</html>

Output:

Explanation:Among all the various elements being present (like Paragraphs and Tables), we are interested to modify only the table table elements.Henceforth, in the first case $("table").css("border", "8px solid #00ff00");we are first selecting all "table" elements present in the DOM tree and then applying the CSS to it(setting the border color).In the next case $("table").css("background-color", "yellow");, we are again selecting all the "table" elements present in the DOM tree and then applying the CSS to it (this time changing the background color).

N.B.~It is better to cache the JQuery object in a variable as it is an inefficient programing practice to call the jQuery function $() repeatedly.So the below is a better way of doing the above program

var $table = $("table");
$table.css("border", "8px solid #00ff00");
$table.css("background-color", "yellow");

A much better way is to implement "JQuery Chaining" for reducing repetition as shown under

var $table = $("table");
$table
.css("border", "8px solid #00ff00")
.css("background-color", "yellow");

People familiar with "Extension Method" of C# (3.0 + ) is aware of this kind of programing style.In this case, first we are selecting all the "table" elements by using selector var $table = $("table");.Then first applying the CSS for setting the border color.The output of this becomes the input for .css("background-color", "yellow");

2.Multiple Element Selectors

Purpose:This kind of selectors are in use if we need to select multiple elements having different attributes.It comes in two flavours -

  1. Intersection:In this case, we write the selectors together without providing any spaces between them.For example, element having Id="MyId" and CSS classes "Class1","Class2", the multiple selector will be $('#MyId.Class1.Class2')
  2. Union:In this case, we write the selectors together by providing spaces between them.For example, element having Id="MyId" and CSS classes "Class1","Class2", the multiple selector will be $("#MyId,.Class1,.Class2")

Multiple Sector - Intersection Example

Objective:We want to set the border color of all the table elements to lightgreen and background color of the tables to "yellow" for those tables whose id starts with "tbl" and has a CSS class by the name "someTableClass"

Code:

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {           
            var $table = $("table[id^=tbl].someTableClass");
            $table
            .css("border", "8px solid #00ff00")
            .css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
     <div id="divMain">
    <h2>Single Selector Example </h2>
        <p>
            I am the first Paragraph
            <table id="tbl1" class="someTableClass">
                    <tr>
                        <td>
                            Col1
                        </td>
                        <td>
                            Col2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            1
                        </td>
                        <td>
                            2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            3
                        </td>
                        <td>
                            4
                        </td>
                    </tr>
                </table>
        </p>
        <p>
            I am the second Paragraph
            <table id="DifferentTableId">
                    <tr>
                        <td>
                            Col1
                        </td>
                        <td>
                            Col2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            1
                        </td>
                        <td>
                            2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            3
                        </td>
                        <td>
                            4
                        </td>
                    </tr>
                </table>
        </p>
        <p>
            <p>
                I am the fourth Paragraph
                <table id="tbl2">
                    <tr>
                        <td>
                            Col1
                        </td>
                        <td>
                            Col2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            1
                        </td>
                        <td>
                            2
                        </td>
                    </tr>
                    <tr>
                        <td>
                            3
                        </td>
                        <td>
                            4
                        </td>
                    </tr>
                </table>
            </p>
            <p>
                I am the fifth Paragraph
            </p>
            I am the third paragraph
        </p>
    </div>
    </form>
</body>
</html>

Output:

Explanation:In this case we are targeting a class name as well as an id pattern on the table.The id pattern should match all tables that starts with "tbl".If we had a requirement of choosing all table having id's that ends with "tbl" e.g. "id = mytbl", then the wildcard expression would have been $("[id$=tbl]")

Multiple Sector - Union Example

Objective:We want to set the border color of all the paragraph and anchor tags to lightgreen and background color to "yellow"

Code:

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('p,a')
            .css("border", "8px solid #00ff00")
           .css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div> I am a div tag</div>
    <p>I am a paragraph</p>
    <span>I am span</span>
    <a href="#">I am anchor tag</a>
    </form>
</body>
</html>

Output:

Explanation:First we are selecting all paragraphs and anchor tags and then applying the CSS style on them

3.Id Selectors

Purpose:For selecting specific elements we invoke them by using "ID" selector.It matches single element with the given id attribute.

Objective:We want to set the border color of the DIV element that has an id 'divID' and change its border to lightgreen and background color to "yellow"

Code:

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#divId')           
            .css("border", "8px solid #00ff00")
            .css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divId">
        I am a valid one
    </div>
    <div id="div1">
        But not I am
    </div>
    </form>
</body>
</html>

Explanation:The way of using the Id selector is to use hash symbol(#) before the element id (#divId).This will match exactly one element in the DOM hierarchy. Once the selection is done, then we can apply the needed CSS styles.

4.CSS Selectors

Purpose:To select elements by CSS class.

Objective:We want to set the border color of the DIV element that has a class as "validClass" and change its border to lightgreen and background color to "yellow"

Code:

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
             $('.validClass')         
            .css("border", "8px solid #00ff00")
            .css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class = "validClass">
        I am a valid one
    </div>
    <div class = "invalidClass">
        But not I am
    </div>
    </form>
</body>
</html>

Explanation:The way of using the CSS selector is to use dot symbol(.) before the element class name (.validClass).This will match exactly those elements in the DOM hierarchy. Once the selection is done, then we can apply the needed CSS styles.

5.Attribute Selectors

Purpose:To select elements based on their attributes and attribute values.

Let us consider that we have the below Html

<html>
<head runat="server">
    <title></title>    
</head>
<body>
    <form id="form1" runat="server">
    <table height="100">
        <tr>
            <td> Col1 </td>
            <td> Col2 </td>
        </tr>
        <tr>
            <td> 1 </td>
            <td> 2 </td>
        </tr>
        <tr>
            <td> 3 </td>
            <td> 4 </td>
        </tr>
    </table>
    <table width="100">
        <tr>
            <td> Col1 </td>
            <td> Col2 </td>
        </tr>
        <tr>
            <td> 1 </td>
            <td> 2 </td>
        </tr>
        <tr>
            <td> 3 </td>
            <td> 4 </td>
        </tr>
    </table>
	<div height="400">I am a div</div>
    </form>
</body>
</html>

We have two TABLES the first one being having a height attribute while the next being width.And finally a DIV with a height attribute

Case 1:We want to choose all elements that have a height attribute

$heightSelector = $('[height]');
$heightSelector
.css("border", "8px solid #00ff00")
.css("background-color", "yellow");

Output:

Explanation:It chooses all elements that has a height attribute.

Case 2:We want to choose all table elements that have a height attribute

$heightSelector = $('table[height]');
$heightSelector
.css("border", "8px solid #00ff00")
.css("background-color", "yellow");

Case 3:We want to choose all table elements that have a width attribute whose value is precisely 200

$heightSelector = $('table[width=100]');
$heightSelector
.css("border", "8px solid #00ff00")
.css("background-color", "yellow");

Case 4:We want to choose all elements that have a height attribute whose value is not 200

 $heightSelector = $('[height!=100]');
$heightSelector
.css("border", "8px solid #00ff00")
.css("background-color", "yellow");

Case 5:We want to choose all table elements that have a height attribute whose value is more than 50

$heightSelector = $('table').filter(function () 
{
	return $(this).attr('height') > 50;
});

$heightSelector
	.css("border", "8px solid #00ff00")
	.css("background-color", "yellow");

Output:

6.Element Visibility Selectors

Purpose:To select elements based on their visibility.

  1. :visiblie
  2. :hidden

e.g.

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var $divSelector = $('#divTest');
            var $isVisible = $divSelector.is(':visible'); //checks for visibility
            if (!$isVisible) 
            {
                $divSelector.toggle(); //toggles the visibility to true

                $divSelector
                .css("border", "8px solid #00ff00")
                .css("background-color", "yellow");
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
		<div id="divTest" style="display:none;">Hello ..I am Div Tag</div>
    </form>
</body>
</html>

Explanation:The code first checks if the div is visible or not. If not , then it toggles the div's visibility and then apply the css styles to the selector

7.Form Field Selectors

Purpose:To select/access the form elements more easily and efficiently in the DOM tree.

Let us consider a simple example

$(':input');

It selects all input fields in the page. The colon(:) before the text input is needed to avoid confusion it with a selection based on element name.The below is a list of form selectors,their purpose, how to get and set values to them

Sl No. Form Selector Name Form Selector Description How to get values How to set values
1 $('input:text') Selects all input fields of type text but not textarea elements. $('input:text').val(); $('input:text').val("Sample text");
2 $('input:password') Selects all input fields of type Password. $('input:password').val(); $('input:password').val("SomePassword");
3 $('input:hidden') Selects all input fields of type hidden. $('input:hidden').val(); $('input:hidden').val("Sample text");
4 $('textarea') Selects Textarea elements. $('textarea').val(); $('textarea').val("Sample text");
5 $('input:file') Selects all input fields of type file. $('input:file').val();
6 $('input:radio') Selects all input fields of type radio. $('input:radio[name=myRadioButton]:checked').val();
  1. $('input[name="myRadioButton"]').attr('checked', true);(before JQuery version 1.6)
  2. $('input[name="myRadioButton"]').prop('checked', true); (after JQuery version 1.6)
7 $('input:checkbox') Selects all input fields of type checkbox. $('input:checkbox[name=myCheckBox]').is(':checked');
  1. $('.myCheckBox').attr('checked','checked')//to check a checkbox

    $('.myCheckBox').removeAttr('checked')//to uncheck a checkbox

    (before JQuery version 1.6)

  2. $(".myCheckBox").prop("checked", true); //to check a checkbox

    $(".myCheckBox").prop("checked", false); //to uncheck a checkbox

    (after JQuery version 1.6)

8 $('select') Selects drop down values. $('#myDropDown').val(); $("#myDropDown").val("Selected Value");
9 $('input:submit') To select Submit button $('input:submit');
10 $('input:reset') To select Reset button $('input:reset');

8.Parent-Child Selectors

Purpose:To select child elements inside the target parent elements.

Let look into it by some simple example

Sl No. Parent-Child Selector Name Parent-Child Selector Description Example Explanation
1 :first-child Selects the first child of a parent element. $('p:first-child'); This example selects the first child of all "p" elements
2 :last-child Selects the last child of a parent element. $('p:last-child'); This example selects the last child of all "p" elements
3 :parent child Select all descendant child element $('p a') This example selects all "a" elements that are descendant of "p".
4 :parent > child Select children of a specific parent element $('div > p'); This example selects all "p" elements inside "div" elements and not outside div elements.
5 :parent + child Select children that are immediate descendant of parent element. $('div + p'); This example selects all "p" elements that are immediate descendant of "div" elements.
6 :parent ~ child Select children that are sibling of parent element. $('div ~ p'); This example selects all "p" elements that are sibling of "div" elements.

References

For a complete list of selectors please visit Selectors

Conclusion

Hope that we have a fair idea by now about selectors and their usage.If not, we will revisit it again and will go through it properly as it is the heart of JQuery and for understanding JQuery concepts properly we need to have a solid foundation of JQuery Selectors.We will proceed to the next section once we are through with the current one.Thanks for reading.The attached zip file contains all the examples being demonstrated here.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)