MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Selectors in jQuery

In this article we will talk about the selectors in jQuery.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

JQuery Selector $() factory function:

Is the first and most important function that is included in the jQuery code for dealing with DOM.

It's clear from its name that it selects element by one of three criterions to be manipulated in jQuery.

The common thing between the three selectors is that they start all with $ and selector is written between rounded parentheses (). $()

Types of selectors:

Selector Look like Description
Id $(“#tag-id”) Selects just one element in the document “id is unique”
Name $(“tagname”) Selects all elements with that name in the document
Class $(“.class-name”) Selects all elements which belongs to the same class in the document

Below we can see an simple demo program.

Listing 1: Simple Demo Program

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>jQuery Tutorial</title>
        <link rel="stylesheet" href="http://code.jQuery.com/ui/1.10.0/themes/base/jQuery-ui.css" />
        <script src="http://code.jQuery.com/jQuery-1.8.3.js"></script>
        <script src="http://code.jQuery.com/ui/1.10.0/jQuery-ui.js"></script>
        <script type="text/javascript">
            function getSelector() {
                // this line will hide the element selected by id immediately on clicked the button
                $("#name").hide();
                //select by class
                var pars = $(".test");
                for (i = 0; i < pars.length; i++) {
                    alert("Found paragraph: " + pars[i].innerHTML);
                }
                // this will select by tag name
                var p = $("p");
                for (i = 0; i < p.length; i++) {
                    alert(p[i].innerHTML);
                }
            }
        </script>
    </head>
    <body>


        Select by id<input type="text" class="test" id="id"/><br/>
        Select by class<input type="text" class="test" id=”class”/><br/>
        Select by name<input type="text" class="test" id=”name”/>
        <p>I am number One</p><br/>
        <p>I am number Two</p>
        <input type="button" onclick="getSelector();" value="click me"/>
    </body>
</html>

So easy and clear, let's see some rules depending on the previously explained rules:

  • $(“*”) : will select all elements in the document , I think it will be useful for localization like retrieving all the elements and put them on right instead of left, etc.
  • $(“tag:not(.classname)”) : it selects all the elements of the written tag but not of the classname specified.
  • $(“tag > anothertag”) : this selects all children “anothertag” under the parent tag “tag” ex: $(“li > ol”)
  • $("sibling + parent"): Selects all elements matched by parent that immediately follow a sibling element matched by sibling.
  • $("tagname:empty") : Selects all elements of that tagname that have no children.
  • $(“:empty”) : Selects all child-less elements in the document
  • $("tagname:visible") : Selects all elements matched by tagname that are visible.
  • $(":checked") : Selects all checked boxes in the form.
  • $(":input") : Selects only form elements.
  • $(":parent") : Selects all parents of another element, including text.
  • $(":text") : Selects only text elements, can be replaced by $(“input[type=text]”).
  • $(":radio") : Selects all radio buttons in the form.
  • $("a[@rel]") : Selects all elements matched by <a> that have a rel attribute.
  • $("tag[anothertag]"): Selects all elements matched by tag, that contain an element matched by anothertag.
  • $(this): as in programming language this refers to the current object “element in our case”.

It's easy to use, read and write. It can be written in a separate file and included as script link in the web page or can be written in the <head> tag as inline script.

Traversing DOM using JQuery:

We mentioned before that DOM traversing is one of the JQuery easy features that can be done with too little code.

Like if we want to deal with a list, each element in the list got an index which is used to access it, so what we need to do to access the element is to get the element by its index and give it a name/class so we have it to change as long as we want.

Let us see another demo:

Listing 2: List in jQuery

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>jQuery Tutorial</title>
        <link rel="stylesheet" href="http://code.jQuery.com/ui/1.10.0/themes/base/jQuery-ui.css" />
        <script src="http://code.jQuery.com/jQuery-1.8.3.js"></script>
        <script src="http://code.jQuery.com/ui/1.10.0/jQuery-ui.js"></script>
        <script type="text/javascript">
            function change() {
                $(document).ready(function() {
                    $("li").eq(2).addClass("selected");
                });
            }
        </script>
        <style>
            .selected
            {
                color:red;
                background: activecaption;
                font-size: large;

            }
        </style>
    </head>
    <body>
        <div>
            <ul>
                <li>list item 1</li>
                <li>list item 2</li>
                <li>list item 3</li>
                <li>list item 4</li>
             
            </ul>
        </div>
        <input type="button" onclick="change();" value="change"/>
    </body>
</html>
Result of Listing 2

Figure 1: Result of Listing 2

On applying an event, the second DOM element is changed color, size and background color.

With the same concept, we can apply filter to my elements by selecting those who following a certain class and apply the change all at the same time as following:

$("li").filter(".classname").addClass("identifier");

Well, now almost we could deal with DOM using JQuery, but one thing need to be considered and then we can go to the full information.

How to Traverse Contents of an Element?

Using .html() methods which is applied to the selector and get the contents of an element as following:

Listing 3: Traversing element Contents

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tutorial</title>
        <link rel="stylesheet" href="http://code.jQuery.com/ui/1.10.0/themes/base/jQuery-ui.css" />
        <script src="http://code.jQuery.com/jQuery-1.8.3.js"></script>
        <script src="http://code.jQuery.com/ui/1.10.0/jQuery-ui.js"></script>
        <script src = "/jQuery/jQuery-1.3.2.min.js" ></script>
        <script type="text/javascript">

          $(document).ready(function() {

                $("#b").click(function() {
                    var content = $("p").html();
                    alert(content);
                    $("#text").text(content);
                });

            });

        </script>
        <style>
            #division{ margin:10px;padding:12px;
                       border:2px solid #666;
                       width:60px;
            }
        </style>
    </head>
    <body>
        <p>Hello World</p><input type="button" id="b"/>
        <p id="text"></p>
    </body>
</html>
       

Figure 2: Output of Listing 3

The previous code get the content of element using .html() method and rewrite it using text(“sometext”) method to another element.

Also the element itself can be replaced in runtime with another element as the following example show using replaceWith() method.

Listing 4: Replacing element

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tutorial</title>
        <link rel="stylesheet" href="http://code.jQuery.com/ui/1.10.0/themes/base/jQuery-ui.css" />
        <script src="http://code.jQuery.com/jQuery-1.8.3.js"></script>
        <script src="http://code.jQuery.com/ui/1.10.0/jQuery-ui.js"></script>
        <script src = "/jQuery/jQuery-1.3.2.min.js" ></script>
        <script type="text/javascript">
                    $(document).ready(function() {

                $("#b").click(function() {
                    var content = $("p");
                    content.replaceWith("<input type='text' value='I am Replaced'/>");
                });

            });

        </script>
        <style>
            #division{ margin:10px;padding:12px;
                       border:2px solid #666;
                       width:60px;
            }
        </style>
    </head>
    <body>
        <p>Hello World</p><input type="button" id="b" value="Click"/>

    </body>
</html>

Figure 3: Result of Listing 4

Finally, To Remove Dom Element just use the method remove(), i.e. select the element and apply remove() to it.

JQuery Events

Since it's necessary to make interactive web pages to satisfy the customer needs. So, events are necessary to such kind of applications.

Like you want to hide element on some event, want to expand it, show another one, display list on the fly, etc.

All that things are provided with the JQuery Events feature.

Some common events that are supported by JQuery are blue: which is occurred when element loses focus or mouse pass over it.

  • change: commonly known for comboboxes.
  • click : similar to onclick in traditional elements
  • load : similar to onload on body tag.

Events methods are assigned to object and include the code to be done in case of being fired like the event click on the previous example:

$("selector").click(function() { });

This is all for this article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login