Tuesday, December 20, 2011

JQuery : Using selectors to get the specific elements

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined. Let's start here.

Here is CSS and script to put <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
    .red { background-color: red;}
    .blue { color: blue;}
    .green { color: green; }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#orderedlist").addClass("red");
        $("#orderedlist > li").addClass("blue");
        $("#orderedlist li:last").hover(function () {
            $(this).addClass("green");
        }, function () {
            $(this).removeClass("green");
        });
    });                
</script>

Add the following to the <body>:
<ol id="orderedlist">
    <li>First element</li>
    <li>Second element</li>
    <li>Third element</li>
</ol>
   
To try some of these selectors, we select and modify the first ordered list in our example.
To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we did it like this:

 $(document).ready(function() {
   $("#orderedlist").addClass("red");
 });

The example provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the ordered list has a red background. I added some more classes to the child elements of this list as below.

 $(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });

This selects all child lis of the element with the id orderedlist and adds the class "blue".
Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list. So, I inserted them to $(document).ready() like below:

   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });

There are many other selectors similar to CSS and XPath syntax.

Full post : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Find_me:_Using_selectors_and_events

Other useful link : http://www.w3schools.com/jquery/jquery_ref_selectors.asp

No comments:

Post a Comment