jQuery selectors examples - jQuery basic tutorial 3

3. jQuery Selectors

The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

The $() factory function:

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().
The factory function $() makes use of following three building blocks while selecting elements in a given document:
jQuery Description
Tag Name: Represents a tag name available in the DOM. For example $('p') selects all paragraphs in the document.
Tag ID: Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id.
Tag Class: Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

Example:

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

How to use Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
Selector Description
Name Selects all elements which match with the given element Name.
#ID Selects a single element which matches with the given ID
.Class Selects all elements which match with the given Class.
Universal (*) Selects all elements available in a DOM.
Multiple Elements E, F, G Selects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.
  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.
  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.
  • $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>
  • $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  • $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  • $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.
  • $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by <p> that have no children.
  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by <p> that have a class value ending with bar
  • $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by <li> that have an even index value.
  • $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.
  • $("li:first"): Selects the first <li> element.
  • $("li:last"): Selects the last <li> element.
  • $("li:visible"): Selects all elements matched by <li> that are visible.
  • $("li:hidden"): Selects all elements matched by <li> that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third <li> element
  • $("li:eq(4)"): Selects the fifth <li> element
  • $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  • $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  • $("li:gt(1)"): Selects all elements matched by <li> after the second one.
  • $("p:gt(2)"): Selects all elements matched by <p> after the third one.
  • $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.
  • $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  • $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>
  • $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.

You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.

jQuery fundamentals - jQuery basic tutorial 2

2. jQuery Fundamentals

jQuery is a framework built using JavaScript capabilities. So you can use all the functions and other capabilities available in JavaScript.
This chapter would explain most basic concepts but frequently used in jQuery.

String:

A string in JavaScript is an immutable object that contains none, one or many characters.
Following are the valid examples of a JavaScript String:
"This is JavaScript String"
'This is JavaScript String'
'This is "really" a JavaScript String'
"This is 'really' a JavaScript String"

Numbers:

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings.
Following are the valid examples of a JavaScript Numbers:
5350 120.27 0.26

Boolean:

A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false:
Following are the valid examples of a JavaScript Boolean:
true      // true
false     // false
0         // false
1         // true
""        // false
"hello"   // true

Objects:

JavaScript supports Object concept very well. You can create an object using the object literal as follows:
var emp = {
name: "Zara",
age: 10
};
You can write and read properties of an object using the dot notation as follows:
// Getting object properties
emp.name  // ==> Zara
emp.age   // ==> 10

// Setting object properties
emp.name = "Daisy"  // <== Daisy
emp.age  =  20      // <== 20

Arrays:

You can define arrays using the array literal as follows:
var x = [];
var y = [1, 2, 3, 4, 5];
An array has a length property that is useful for iteration:
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++) {
   // Do something with x[i]
 }

Functions:

A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows:
function named(){
// do some stuff here
}
An anonymous function can be defined in similar way as a normal function but it would not have any name.
A anonymous function can be assigned to a variable or passed to a method as shown below.
var handler = function (){
// do some stuff here
}
JQuery makes a use of anonymous functions very frequently as follows:
$(document).ready(function(){
// do some stuff here
});

Arguments:

JavaScript variable arguments is a kind of array which has length property. Following example explains it very well:
function func(x){
console.log(typeof x, arguments.length);
}
func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3
The arguments object also has a callee property, which refers to the function you're inside of. For example:
function func() {
return arguments.callee; 
}
func();                // ==> func

Context:

JavaScript famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called:
$(document).ready(function() {
// this refers to window.document
});

$("div").click(function() {
  // this refers to a div DOM element
});
You can specify the context for a function call using the function-built-in methods call() and apply() methods.
The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.
function scope() {
console.log(this, arguments.length);
}

scope() // window, 0
scope.call("foobar", [1,2]);  //==> "foobar", 1
scope.apply("foobar", [1,2]); //==> "foobar", 2

Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
  • Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.
  • Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name:
var myVar = "global";     // ==> Declare a global variable

function ( ) {
   var myVar = "local";   // ==> Declare a local variable
   document.write(myVar); // ==> local
}

Callback:

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.
jQuery's event system uses such callbacks everywhere for example:
$("body").click(function(event) {
console.log("clicked: " + event.target);
 });
Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event.
Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows:
$("#myform").submit(function() {
return false;
 });

Closures:

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.
Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them:
  function create() {
  var counter = 0;
  return {
    increment: function() {
      counter++;
    },
    print: function() {
      console.log(counter);
    }
  }
}
var c = create();
c.increment();
c.print();     // ==> 1
This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming.

Proxy Pattern:

A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject.
A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows:
  (function() {
  // log all calls to setArray
  var proxied = jQuery.fn.setArray;

  jQuery.fn.setArray = function() {
    console.log(this, arguments);
    return proxied.apply(this, arguments);
  };
})();
The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.

Built-in Functions:

JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates.
Following are important JavaScript functions:
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
forEach() Calls a function for each element in the array.
indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
length() Returns the length of the string.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the array.
reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
sort() Sorts the elements of an array.
substr() Returns the characters in a string beginning at the specified location through the specified number of characters.
toLowerCase() Returns the calling string value converted to lower case.
toString() Returns the string representation of the number's value.
toUpperCase() Returns the calling string value converted to uppercase.
  

The Document Object Model:

The Document Object Model is a tree structure of various elements of HTML as follows:
<html>
<head>
   <title>the title</title>
</head>
<body>
   <div>
      <p>This is a paragraph.</p>
      <p>This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>
Following are the important points about the above tree structure:

  • The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.
  • The <head> and <body> elements are not only descendants, but children of <html>, as well.
  • Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.
  • The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

jQuery overview - jQuery basic tutorial series 1

jQuery Introduction :

jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery:

  • DOM manipulation: The jQuery made it easy to select DOM elements, traverse them and modifying their content by using cross-browser open source selector engine called Sizzle.
  • Event handling: The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
  • AJAX Support: The jQuery helps you a lot to develop a responsive and feature-rich site using AJAX technology.
  • Animations: The jQuery comes with plenty of built-in animation effects which you can use in your websites.
  • Lightweight: The jQuery is very lightweight library - about 19KB in size ( Minified and gzipped ).
  • Cross Browser Support: The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
  • Latest Technology: The jQuery supports CSS3 selectors and basic XPath syntax.
  • How to use jQuery library?

    Now you can include jquery library in your HTML file as follows:
    <html>
    <head>
    <title>The jQuery Example</title>
       <script type="text/javascript" 
       src="/jquery/jquery-1.3.2.min.js"></script>
       <script type="text/javascript">
          // you can add our javascript code here 
       </script>   
    </head>
    <body>
    ........
    </body>
    </html>
    
    

    How to call a jQuery library functions?

    As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
    If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
    To do this, we register a ready event for the document as follows:
    $(document).ready(function() { // do stuff when DOM is ready });
  • To call upon any jQuery library function, use HTML script tags as shown below:
    <html>
    <head>
    <title>The jQuery Example</title>
       <script type="text/javascript" 
       src="/jquery/jquery-1.3.2.min.js"></script>
       
       <script type="text/javascript" language="javascript">
       // <![CDATA[
       $(document).ready(function() {
          $("div").click(function() {
            alert("Hello world!");
          });
       });
       // ]]>
       </script>
    
    </head>
    <body>
    <div id="newdiv">
    Click on this to see a dialogue box.
    </div>
    </body>
    </html>
    
    

    How to use Custom Scripts?

    It is better to write our custom code in the custom JavaScript file : custom.js, as follows:
  •     
    /* Filename: custom.js */
    $(document).ready(function() {
      $("div").click(function() {
     alert("Hello world!");
      });
    });
    Now we can include custom.js file in our HTML file as follows:
    
    <html>
    <head>
    <title>The jQuery Example</title>
       <script type="text/javascript" 
       src="/jquery/jquery-1.3.2.min.js"></script>
       <script type="text/javascript" 
       src="/jquery/custom.js"></script>
    </head>
    <body>
    <div id="newdiv">
    Click on this to see a dialogue box.
    </div>
    </body>
    </html>