Friday, March 5, 2010

Jquery Basic Knowledge

1. Give me an example of ready function in Jquery?

      $(document).ready(function() {
      $('p').addClass('highlight');
      });
      ready function is declared as "$(document).ready()".


2. How ready function works in Jquery?


   "$(document).ready()"  This method executes the function call when the DOM is loaded and ready.
Example:
$(document).ready(function() {
$('p').addClass('highlight');
});


We use the function keyword (without the function name) and define the body of the function to use when the DOM has loaded. The function body is used as an argument to the method for the simple reason that we want the function to be executed immediately, but once only. We don’t want it to be reused again. In other words, $(document).ready() registers a ready event for the document.
The $('p') in the preceding solution is a selector that accesses the paragraph elements of the HTML. file, and to those elements the addClass() method will apply the specified CSS class.


3.How we select the nodes using $()?


     • $('p')—Accesses all the paragraph elements in the HTML file
     • $('div')—Accesses all the div elements in the HTML file
     • $('#A')—Accesses all the HTML elements with id=A
     • $('.b')—Accesses all the HTML elements with class=b
     Example:
     $(document).ready(function() {
     $('p').addClass('highlight'); //'highlight' is the css class
     });
4.How you count the number of nodes in the DOM and display its text?

Solution


Jquery

$(document).ready(function() {

var $nodes = $('#root').children();
alert('Number of nodes is '+$nodes.length);
var str="";
$('#root').children().each( function() {
str+=$(this).text();
});
alert(str);
});

5. How we use  ".each()", ".text()", ".childeren()" in jquery methods?
  • children(): The children() method is a tree-traversal method that searches for the immediate children of the specified element and returns a new jQuery object. This method travels only a single level down in the DOM tree. 
  • each():each() is a method that is used to iterate over each element in the wrapped collection.
  • text(): text() is a method of the jQuery object that accesses the text contents of the selected element(s). Exanple: alert($('p').text());
  • parent(): The parent() method is a tree-traversal method that searches for the immediate parent of each of the selected elements and returns a new jQuery object. This method travels only a single level up in the DOM treeExample:
       alert($('span').parent().text());

6. COMMING SOON.

0 comments: