Category: Basic

  • Replace Elements

    jQuery provides replaceWith() method to replace existing HTML content with a new content in a given HTML document.

    jQuery replaceWith() Method

    The jQuery replaceWith() method removes the content from the DOM and inserts a new content in it’s place.

    Following is the syntax of the replaceWith() method:

    $(selector).replaceWith(newContent);

    The replaceWith() method removes all data and event handlers associated with the removed nodes.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery replaceWith() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div><div class="hello">Hello</div></div>

    Now if we apply the replaceWith() method as follows:

    $(".hello").replaceWith("<h2>New Element</h2>");

    It will produce following result:

    <div class="container"><h2>jQuery remove() Method</h2><h2>New Element</h2><div class="goodbye">Goodbye</div><h2>New Element</h2></div>

    If we had any number of nested elements inside <div class=”hello”>, they would be removed, too.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".hello").replaceWith("<h2>New Element</h2>");});});</script></head><body><div class="container"><h2>jQuery replaceWith() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div><div class="hello">Hello</div></div><br><button>Replace Element</button></body></html>

    Example

    Following example replace all paragraphs with Brilliant.

    <!doctype html><html lang="en"><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("p").replaceWith("<b>Brilliant</b>");});});</script></head><body><h2>jQuery replaceWith() Method</h2><p>Zara</p><p>Nuha</p><p>Ayan</p><button>Replace Element</button></body></html>

    jQuery HTML/CSS Reference

    You can get a complete reference of all the jQuery Methods to manipulate CSS and HTML content at the following page: jQuery HTML/CSS Reference.

  • Remove Elements

    jQuery provides remove() and empty() methods to remove existing HTML elements from an HTML document.

    jQuery remove() Method

    The jQuery remove() method removes the selected element(s) and it’s child elements from the document.

    Following is the syntax of the remove() method:

    $(selector).remove();

    You should use remove() method when you want to remove the element itself, as well as everything inside it.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery remove() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div></div>

    Now if we apply the remove() method as follows:

    $(".hello").remove();

    It will produce following result:

    <div class="container"><h2>jQuery remove() Method</h2><div class="goodbye">Goodbye</div></div>

    If we had any number of nested elements inside <div class=”hello”>, they would be removed, too.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".hello").remove();});});</script></head><body><div class="container"><h2>jQuery remove() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div></div><br><button>Remove Text</button></body></html>

    Remove with Filter

    We can also include a selector as an optional parameter for the remove() method. For example, we could rewrite the previous DOM removal code as follows:

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("div").remove(".hello");});});</script></head><body><div class="container"><h2>jQuery remove(selector) Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div></div><br><button>Remove Text</button></body></html>

    jQuery empty() Method

    The jQuery empty() method is very similar to remove() which removes the selected element(s) and it’s child elements from the document. This method does not accept any arguments.

    Following is the syntax of the empty() method:

    $(selector).empty();

    You should use empty() method when you want to remove the element itself, as well as everything inside it.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery empty() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div></div>

    Now if we apply the empty() method as follows:

    $(".hello").empty();

    It will produce following result:

    <div class="container"><h2>jQuery empty() Method</h2><div class="goodbye">Goodbye</div></div>

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".hello").empty();});});</script></head><body><div class="container"><h2>jQuery empty() Method</h2><div class="hello">Hello</div><div class="goodbye">Goodbye</div></div><br><button>Remove Text</button></body></html>

    jQuery HTML/CSS Reference

    You can get a complete reference of all the jQuery Methods to manipulate CSS and HTML content at the following page: jQuery HTML/CSS Reference.

  • Add Elements

    jQuery provides various methods to add new DOM elements in the existing HTML document. You can add these new elements at various locations (before, after any of the existing tags) based on your requirements.

    jQuery append() Method

    The jQuery append() method adds the content at the end of the matched each element(s). You can also append multiple elements in a single function call.

    Following is the syntax of the append() method:

    $(selector).append(content,[content]);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery append() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div>

    Now if we apply the append() method as follows:

    $(".inner").append("<p>Zara</p>");

    It will produce following result:

    <div class="container"><h2>jQuery append() Method</h2><div class="inner">Hello
       <p>Zara</p></div><div class="inner">Goodbye
       <p>Zara</p></div></div>

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".inner").append("<p>Zara</p>");});});</script></head><body><div class="container"><h2>jQuery append() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery appendTo() Method

    The jQuery appendTo() method performs the same task as done by appendTo(). The major difference is in the syntax-specifically, in the placement of the content and target.

    Following is the syntax of the appendTo() method:

    $(content).appendTo(selector);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("<p>Zara</p>").appendTo(".inner");});});</script></head><body><div class="container"><h2>jQuery appendTo() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery after() Method

    The jQuery after() method adds the content after the matched each element(s). You can also insert multiple elements in a single function call.

    Following is the syntax of the after() method:

    $(selector).after(content,[content]);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery after() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div>

    Now if we apply the after() method as follows:

    $(".inner").after("<p>Zara</p>");

    It will produce following result:

    <div class="container"><h2>jQuery after() Method</h2><div class="inner">Hello</div><p>Zara</p><div class="inner">Goodbye</div><p>Zara</p></div>

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".inner").after("<p>Zara</p>");});});</script></head><body><div class="container"><h2>jQuery after() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery insertAfter() Method

    The jQuery insertAfter() method adds the content after the matched each element(s). The after() and insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target.

    Following is the syntax of the after() method:

    $(content).insertAfter(selector);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("<p>Zara</p>").insertAfter(".inner");});});</script></head><body><div class="container"><h2>jQuery insertAfter() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery prepend() Method

    The jQuery prepend() method adds the content at the beginning of the matched each element(s). You can also prepend multiple elements in a single function call.

    Following is the syntax of the append() method:

    $(selector).prepend(content,[content]);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery prepend() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div>

    Now if we apply the prepend() method as follows:

    $(".inner").prepend("<p>Zara</p>");

    It will produce following result:

    <div class="container"><h2>jQuery prepend() Method</h2><div class="inner"><p>Zara</p>
       Hello
       </div><div class="inner"><p>Zara</p>
       Goodbye
       </div></div>

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".inner").prepend("<p>Zara</p>");});});</script></head><body><div class="container"><h2>jQuery prepend() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery prependTo() Method

    The jQuery prependTo() method perform the same task as done by prepend(). The major difference is in the syntax-specifically, in the placement of the content and target.

    Following is the syntax of the prependTo() method:

    $(content).prependTo(selector);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("<p>Zara</p>").prependTo(".inner");});});</script></head><body><div class="container"><h2>jQuery prependTo() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery before() Method

    The jQuery before() method adds the content before the matched each element(s). You can also insert multiple elements in a single function call.

    Following is the syntax of the before() method:

    $(selector).before(content,[content]);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Synopsis

    Consider the following HTML content:

    <div class="container"><h2>jQuery before() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div>

    Now if we apply the before() method as follows:

    $(".inner").before("<p>Zara</p>");

    It will produce following result:

    <div class="container"><h2>jQuery before() Method</h2><p>Zara</p><div class="inner">Hello</div><p>Zara</p><div class="inner">Goodbye</div></div>

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".inner").before("<p>Zara</p>");});});</script></head><body><div class="container"><h2>jQuery before() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery insertBefore() Method

    The jQuery insertBefore() method adds the content before the matched each element(s). The before() and insertBefore() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target.

    Following is the syntax of the after() method:

    $(content).insertBefore(selector);

    Here content parameter could be a HTML string, a DOM element, text node, array of elements and text nodes or jQuery object to insert at the end of each element in the set of matched elements.

    Example

    Let’s try the following example and verify the result:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("<p>Zara</p>").insertBefore(".inner");});});</script></head><body><div class="container"><h2>jQuery insertBefore() Method</h2><div class="inner">Hello</div><div class="inner">Goodbye</div></div><br><button>Add Text</button></body></html>

    jQuery HTML/CSS Reference

    You can get a complete reference of all the jQuery Methods to manipulate CSS and HTML content at the following page: jQuery HTML/CSS Reference.

  • DOM Manipulation

    jQuery provides a number of methods to manipulate DOM in efficient way. You do not need to write big and complex code to set or get the content of any HTML element.

    jQuery DOM Manipulation

    jQuery provides methods such as attr()html()text() and val() which act as getters and setters to manipulate the content from HTML documents.

    Document Object Model (DOM) – is a W3C (World Wide Web Consortium) standard that allows us to create, change, or remove elements from the HTML or XML documents.

    Here are some basic operations which you can perform on DOM elements with the help of jQuery standard library methods −

    • Extract the content of an element
    • Change the content of an element
    • Adding a child element under an existing element
    • Adding a parent element above an existing element
    • Adding an element before or after an existing element
    • Replace an existing element with another element
    • Delete an existing element
    • Wrapping content with-in an element

    We have already covered attr() method while discussing jQuery Attributes and remaining DOM content manipulation methods html()text() and val() will be discussed in this chapter.

    jQuery – Get Content

    jQuery provides html() and text() methods to extract the content of the matched HTML element. Following is the syntax of these two methods:

    $(selector).html();$(selector).text();

    The jQuery text() method returns plain text value of the content where as html() returns the content with HTML tags. You will need to use jQuery selectors to select the target element.

    Example

    Following example shows how to get the content with the jQuery text() and html() methods:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#text").click(function(){alert($("p").text());});$("#html").click(function(){alert($("p").html());});});</script></head><body><p>The quick <b>brown fox</b> jumps over the <b>lazy dog</b></p><button id="text">Get Text</button><button id="html">Get HTML</button></body></html>

    Get Form Fields

    jQuery val() method is used to get the value from any form field. Following is simple syntax of this method.

    $(selector).val();

    Example

    Following is another example to show how to get the value an input field with jQuery method val() −

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#b1").click(function(){alert($("#name").val());});$("#b2").click(function(){alert($("#class").val());});});</script></head><body><p>Name:<input type="text" id="name" value="Zara Ali"/></p><p>Class:<input type="text" id="class" value="Class 12th"/></p><button id="b1">Get Name</button><button id="b2">Get Class</button></body></html>

    jQuery – Set Content

    jQuery html() and text() methods can be used to set the content of the matched HTML element. Following is the syntax of these two methods when they are used to set the values:

    $(selector).html(val,[function]);$(selector).text(val,[function]);

    Here val is he HTML of text content to be set for the element. We can provide an optional callback function to these methods which will be called when the value of the element will be set.

    The jQuery text() method sets plain text value of the content where as html() method sets the content with HTML tags.

    Example

    Following example shows how to set the content of an element with the jQuery text() and html() methods:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#text").click(function(){$("p").text("The quick <b>brown fox</b> jumps over the <b>lazy dog</b>");});$("#html").click(function(){$("p").html("The quick <b>brown fox</b> jumps over the <b>lazy dog</b>");});});</script></head><body><p>Click on any of the two buttons to see the result</p><button id="text">Set Text</button><button id="html">Set HTML</button></body></html>

    Set Form Fields

    jQuery val() method is also used to set the value from any form field. Following is simple syntax of this method when it is used to set the value.

    $(selector).val(val);

    Here val is he value to be set for the input field. We can provide an optional callback function which will be called when the value of the field will be set.

    Example

    Following is another example to show how to set the value an input field with jQuery method val() −

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#b1").click(function(){$("#name").val("Zara Ali");});$("#b2").click(function(){$("#class").val("Class 12th");});});</script></head><body><p>Name:<input type="text" id="name" value=""/></p><p>Class:<input type="text" id="class" value=""/></p><button id="b1">Set Name</button><button id="b2">Set Class</button></body></html>

    jQuery – Replacement Elements

    The jQuery replaceWith() method can be used to replace a complete DOM element with another HTML or DOM element. Following is the syntax of the method:

    $(selector).replaceWith(val);

    Here val is what you want to have instead of original element. This could be HTML or simple text.

    Example

    Following is an example where we will replace a <p> element with an <h1> element and then further we replace <h1> element with <h2> element.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#b1").click(function(){$("p").replaceWith("<h1>This is new heading</h1>");});$("#b2").click(function(){$("h1").replaceWith("<h2>This is another heading</h2>");});});</script></head><body><p>Click below button to replace me</p><button id="b1">Replace Paragraph</button><button id="b2">Replace Heading</button></body></html>

    jQuery HTML/CSS Reference

    You can get a complete reference of all the jQuery Methods to manipulate CSS and HTML content at the following page: jQuery CSS/HTML Reference.

  • Ajax

    AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.

    If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.

    JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.

    Loading Simple Data

    This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job −

    Syntax

    Here is the simple syntax for load() method −

    [selector].load( URL, [data], [callback] );
    

    Here is the description of all the parameters −

    • URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
    • data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
    • callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.

    Example

    Consider the following HTML file with a small JQuery coding −

    <html><head><title>The jQuery Example</title><script type = "text/javascript" 
    
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"&gt;&lt;/script&gt;&lt;script type = "text/javascript" language = "javascript"&gt;
         $(document).ready(function() {
            $("#driver").click(function(event){
               $('#stage').load('/jquery/result.html');
            });
         });
      &lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click on the button to load /jquery/result.html file −&lt;/p&gt;&lt;div id = "stage" style = "background-color:cc0;"&gt;
         STAGE
      &lt;/div&gt;&lt;input type = "button" id = "driver" value = "Load Data" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line −

    <h1>THIS IS RESULT...</h1>
    

    When you click the given button, then result.html file gets loaded.https://www.tutorialspoint.com/jquery/src/loading-simple-data.htm

    Getting JSON Data

    There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action.

    Syntax

    Here is the simple syntax for getJSON() method −

    [selector].getJSON( URL, [data], [callback] );
    

    Here is the description of all the parameters −

    • URL − The URL of the server-side resource contacted via the GET method.
    • data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.
    • callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.

    Example

    Consider the following HTML file with a small JQuery coding −

    <html><head><title>The jQuery Example</title><script type = "text/javascript" 
    
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"&gt;&lt;/script&gt;&lt;script type = "text/javascript" language = "javascript"&gt;
         $(document).ready(function() {
            $("#driver").click(function(event){
    			
               $.getJSON('/jquery/result.json', function(jd) {
                  $('#stage').html('&lt;p&gt; Name: ' + jd.name + '&lt;/p&gt;');
                  $('#stage').append('&lt;p&gt;Age : ' + jd.age+ '&lt;/p&gt;');
                  $('#stage').append('&lt;p&gt; Sex: ' + jd.sex+ '&lt;/p&gt;');
               });
    				
            });
         });
      &lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click on the button to load result.json file −&lt;/p&gt;&lt;div id = "stage" style = "background-color:#eee;"&gt;
         STAGE
      &lt;/div&gt;&lt;input type = "button" id = "driver" value = "Load Data" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our result.json file has following json formatted content −

    {
       "name": "Zara Ali",
       "age" : "67",
       "sex": "female"
    }
    

    When you click the given button, then result.json file gets loaded.https://www.tutorialspoint.com/jquery/src/getting-json-data.htm

    Passing Data to the Server

    Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method.

    Example

    This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it −

    <html><head><title>The jQuery Example</title><script type = "text/javascript" 
    
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"&gt;&lt;/script&gt;&lt;script type = "text/javascript" language = "javascript"&gt;
         $(document).ready(function() {
            $("#driver").click(function(event){
               var name = $("#name").val();
               $("#stage").load('/jquery/result.php', {"name":name} );
            });
         });
      &lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Enter your name and click on the button:&lt;/p&gt;&lt;input type = "input" id = "name" size = "40" /&gt;&lt;br /&gt;&lt;div id = "stage" style = "background-color:cc0;"&gt;
         STAGE
      &lt;/div&gt;&lt;input type = "button" id = "driver" value = "Show Result" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Here is the code written in result.php script −

    <?php
       if( $_REQUEST["name"]){
    
      $name = $_REQUEST['name'];
      echo "Welcome ". $name;}?&gt;</pre>

    Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box.https://www.tutorialspoint.com/jquery/src/passing-data-to-server.htm

    JQuery AJAX Methods

    You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need −

    Sr.No.Methods & Description
    1jQuery.ajax( options )Load a remote page using an HTTP request.
    2jQuery.ajaxSetup( options )Setup global settings for AJAX requests.
    3jQuery.get( url, [data], [callback], [type] )Load a remote page using an HTTP GET request.
    4jQuery.getJSON( url, [data], [callback] )Load JSON data using an HTTP GET request.
    5jQuery.getScript( url, [callback] )Loads and executes a JavaScript file using an HTTP GET request.
    6jQuery.post( url, [data], [callback], [type] )Load a remote page using an HTTP POST request.
    7load( url, [data], [callback] )Load HTML from a remote file and inject it into the DOM.
    8serialize( )Serializes a set of input elements into a string of data.
    9serializeArray( )Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.

    JQuery AJAX Events

    You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available −

    You can go through all the AJAX Events.

    Sr.No.Methods & Description
    1ajaxComplete( callback )Attach a function to be executed whenever an AJAX request completes.
    2ajaxStart( callback )Attach a function to be executed whenever an AJAX request begins and there is none already active.
    3ajaxError( callback )Attach a function to be executed whenever an AJAX request fails.
    4ajaxSend( callback )Attach a function to be executed before an AJAX request is sent.
    5ajaxStop( callback )Attach a function to be executed whenever all AJAX requests have ended.
    6ajaxSuccess( callback )Attach a function to be executed whenever an AJAX request completes successfully.

  • Attributes Manipulation

    jQuery is being heavily used in manipulating various attributes associated with HTML elements. Every HTML element can have various standard and custom attributes (i.e. properties) which are used to define the characteristics of that HTML element.

    jQuery gives us the means to easily manipulate (Get and Set) an element’s attributes. First let’s try to understand a little about HTML standard and custom attributes.

    Standard Attributes

    Some of the more common attributes are −

    • className
    • tagName
    • id
    • href
    • title
    • rel
    • src
    • style

    Example

    Let’s have a look at the following code snippet for HTML markup for an image element −

    <img id="id" src="image.gif" alt="Image"class="class" title="This is an image"/>

    In this element’s markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element’s attributes, each of which consists of a name and a value.

    Custom data-* Attributes

    HTML specification allows us to add our own custom attributes with the DOM elements to provide additional detail about the element. These attributes names start with data-.

    Example

    Below is an example where we provided information about copyright of the image using data-copyright which is a custom attribute −

    <img data-copyright="Tutorials Point" id="imageid" src="image.gif" alt="Image"/>

    jQuery – Get Standard Attributes

    jQuery attr() method is used to fetch the value of any standard attribute from the matched HTML element(s). We will use jQuery Selectors to match the desired element(s) and then we will apply attr() method to get the attribute value for the element.

    If given selector matches more than one elements then it returns the list of values which you can iterate through using jQuery Array methods.

    Example

    Following is a jQuery program to get href and title attributes of an anchor <a> element:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){alert("Href = "+$("#home").attr("href"));alert("Title = "+$("#home").attr("title"));});});</script></head><body><p>Click the below button to see the result:</p><p><a id="home" href="index.htm" title="Tutorials Point">Home</a></p><button>Get Attribute</button></body></html>

    jQuery – Get Data Attributes

    jQuery data() method is used to fetch the value of any custom data attribute from the matched HTML element(s). We will use jQuery Selectors to match the desired element(s) and then we will apply data() method to get the attribute value for the element.

    Example

    Following is a jQuery program to get author-name and year attributes of a <div> element:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){alert("Author = "+$("#home").data("author-name"));alert("Year = "+$("#home").data("year"));});});</script></head><body><p>Click the below button to see the result:</p><div id="home" data-author-name="Zara Ali" data-year="2022">
    
      Just an Example Content
    </div><br><button>Get Attribute</button></body></html>

    jQuery – Set Standard Attributes

    jQuery attr(name, value) method is used to set the value of any standard attribute of the matched HTML element(s). We will use jQuery Selectors to match the desired element(s) and then we will apply attr(key, value) method to set the attribute value for the element.

    If given selector matches more than one elements then it will set the value of the attribute for all the matched elements.

    Example

    Following is a jQuery program to set the title attribute of an anchor <a> element:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("#home").attr("title","New Anchor Title");/* Let's get and display changed title */alert("Changed Title = "+$("#home").attr("title"));});});</script></head><body><p>Click the below button to see the result:</p><p><a id="home" href="index.htm" title="Tutorials Point">Home</a></p><button>Set Attribute</button><p>You can hover the Home link to verify the title before and after the change.</p></body></html>

    jQuery – Set Custom Attributes

    jQuery data(name, value) method is used to set the value of any custom attribute of the matched HTML element(s). We will use jQuery Selectors to match the desired element(s) and then we will apply attr(key, value) method to set the attribute value for the element.

    If given selector matches more than one elements then it will set the value of the attribute for all the matched elements.

    Example

    Following is a jQuery program to set author-name attribute of a <div> element:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("button").click(function(){$("#home").data("author-name","Nuha Ali");/* Let's get and display changed author name */alert("Changed Name = "+$("#home").data("author-name"));});});</script></head><body><p>Click the below button to see the result:</p><div id="home" data-author-name="Zara Ali" data-year="2022">
    
      Just an Example Content
    </div><br><button>Set Attribute</button></body></html>

    jQuery HTML/CSS Reference

    You can get a complete reference of all the jQuery Methods to manipulate HTML and CSS content at the following page: jQuery HTML/CSS Reference.

  • Event Handling

    Any modern web application can’t be imagined without an event associated with it. Events are the mechanism to build an interactive web page. jQuery is smart enough to handle any event generated on an HTML page. First let’s try to understand what is an event.

    What are jQuery Events?

    A jQuery Event is the result of an action that can be detected by jQuery (JavaScript). When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions are called Event Handlers.

    The jQuery library provides methods to handle all the DOM events and make complete event handling considerably easier than what we have available in JavaScript.

    Following are the examples of some common events −

    • A mouse click
    • A web page loading
    • Taking mouse over an element
    • Submitting an HTML form
    • A keystroke on your keyboard, etc.

    The following table lists some of the important DOM events.

    Mouse EventsKeyboard EventsForm EventsDocument Events
    clickkeypresssubmitload
    dblclickkeydownchangeresize
    hoverkeyupselectscroll
    mousedownblurunload
    mouseupfocusinready

    This chapter coveres only few event methods and properties, For a complete reference of all the jQuery Event Methods and Properties, you can go to through jQuery Events Reference.

    jQuery Event Binding Syntax

    Consider a situation when you want to click a <div> in an HTML document and then you want to perform some action against this click. To achieve this you will have to bind a jQuery click event with the <div> element and then define an action against the click event.

    Following is jQuery syntax to bind a click event with all the <div> elements available in an HTML document:

    $("div").click();

    The next step is to define an action against the click event. Following is the syntax to define a function which will be executed when click event will be fired. This function is called jQuery Event Handler

    $("div").click(function(){// jQuery code goes here});

    Following is another syntax to bind a click event with any of the DOM elements:

    $("div").bind('click',function(){// jQuery code goes here});

    jQuery Event Examples

    jQuery click Event

    Following is an example to bind a click event with <div> where an alert box is displayed whenever you click on any of the divs. Try to click the icon run button to run the following jQuery code:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").click(function(){alert('Hi there!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Click on any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery dblclick Event

    Let’s re-write the above code to bind a dblclick event with <div> where an alert box is displayed whenever you double click on any of the divs.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").dblclick(function(){alert('Hi there!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Double click on any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery mouseenter Event

    Following is an example to bind a mouseenter event with <div> where an alert box is displayed whenever you bring cursor over any of the divs.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").mouseenter(function(){alert('Cursor is in!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Bring cursor over any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery mouseleave Event

    Following is an example to bind a mouseleave event with <div> where an alert box is displayed whenever you take cursor out of the div.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").mouseleave(function(){alert('Curosr is out!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Take cursor out any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery mousedown Event

    Following is an example to bind a mousedown event with <div> where an alert box is displayed whenever the left, middle or right mouse button is pressed down over any of the divs.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").mousedown(function(){alert('Mouse button is down!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Press mouse button down over any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery mouseup Event

    Following is an example to bind a mouseup event with <div> where an alert box is displayed whenever the left, middle or right mouse button is released over any of the divs.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").mouseup(function(){alert('Mouse button is released!');});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Release mouse button over any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    jQuery Event Object

    Whenever a jQuery event is fired, jQuery passes an Event Object to every event handler function.The event object provides various useful information about the event.

    The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed.

    The following event properties/attributes are available and safe to access in a platform independent manner −

    PropertyDescription
    altKeySet to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
    ctrlKeySet to true if the Ctrl key was pressed when the event was triggered, false if not.
    dataThe value, if any, passed as the second parameter to the bind() command when the handler was established.
    keyCodeFor keyup and keydown events, this returns the key that was pressed.
    metaKeySet to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
    pageXFor mouse events, specifies the horizontal coordinate of the event relative from the page origin.
    pageYFor mouse events, specifies the vertical coordinate of the event relative from the page origin.
    relatedTargetFor some mouse events, identifies the element that the cursor left or entered when the event was triggered.
    screenXFor mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
    screenYFor mouse events, specifies the vertical coordinate of the event relative from the screen origin.
    shiftKeySet to true if the Shift key was pressed when the event was triggered, false if not.
    targetIdentifies the element for which the event was triggered.
    timeStampThe timestamp (in milliseconds) when the event was created.
    typeFor all events, specifies the type of event that was triggered (for example, click).
    whichFor keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right).

    Example

    Following is an example to show how different square clicks give different coordinates.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").click(function(eventObj){alert('Event type is '+ eventObj.type);alert('pageX : '+ eventObj.pageX);alert('pageY : '+ eventObj.pageY);alert('Target : '+ eventObj.target.innerHTML);});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Click on any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    this Keyword in Event Handler

    Many times it becomes very easy to make use of this keyword inside an event handler. This keyword represents a DOM element which triggers the event.

    Following example will show the content of the clicked <div>:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("div").click(function(){alert($(this).text());});});</script><style>
       div{ margin:10px;padding:12px; border:2px solid #666; width:60px;cursor:pointer}</style></head><body><p>Click on any of the squares to see the result:</p><div>One</div><div>Two</div><div>Three</div></body></html>

    Removing Event Handlers

    Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

    jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −

    selector.unbind(eventType, handler)
    
    or 
    
    selector.unbind(eventType)
    

    Following is the description of the parameters −

    • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
    • handler − If provided, identifies the specific listener that’s to be removed.

    jQuery Events Reference

    You can get a complete reference of all the jQuery Event Methods and Properties at the following page: jQuery Events Reference.

  • Selectors

    The most important functionality of jQuery is provided by it’s Selectors. This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors.

    jQuery Selectors

    jQuery Selectors are used to select HTML element(s) from an HTML document. Consider an HTML document is given and you need to select all the <div> from this document. This is where jQuery Selectors will help.

    jQuery Selectors can find HTML elements (ie. Select HTML elements) based on the following:

    • HTML element Name
    • Element ID
    • Element Class
    • Element attribute name
    • Element attribute value
    • Many more criteria

    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).

    jQuery Selectors works in very similar way on an HTML document like an SQL Select Statement works on a Database to select the records.

    jQuery Selector Syntax

    Following is the jQuery Selector Syntax for selecting HTML elements:

    $(document).ready(function(){$(selector)});

    A jQuery selector starts with a dollar sign $ and then we put a selector inside the braces (). Here $() is called factory function, which makes use of following three building blocks while selecting elements in a given document:

    Selector NameDescription
    The element SelectorRepresents an HTML element name available in the DOM. For example $(‘p’) selects all paragraphs <p> in the document.
    The #id SelectorRepresents a HTML element available with the given ID in the DOM. For example $(‘#some-id’) selects the single element in the document that has some-id as element Id.
    The .class SelectorRepresents a HTML elements 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 selectors 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.

    The element Selector

    The jQuery element selector selects HTML element(s) based on the element name. Following is a simple syntax of an element selector:

    $(document).ready(function(){$("Html Element Name")});

    Please note while using element name as jQuery Selector, we are not giving angle braces alongwith the element. For example, we are giving only plain p instead of <p>.

    Examples

    Following is an example to select all the <p> elements from an HTML document and then change the background color of those paragraphs. You will not see any <p> element in the output generated by this example. You can also change the code to use different element names as selector and then click the icon run button to verify the result.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("p").css("background-color","yellow");});</script></head><body><h1>jQuery element Selector</h1><p>This is p tag</p><span>This is span tag</span><div>This is div tag</div></body></html>

    The #id Selector

    The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector:

    $(document).ready(function(){$("#id of the element")});

    To use jQuery #id selector, you need to make sure that id attribute should be uniquely assigned to all the DOM elements. If your elements will have similar ids then it will not produce correct result.

    Examples

    Following is an example to select the <p> element whose id is foo and change the background color of those paragraphs.. You can also change the code to use different element id attribute as selector and then click the icon run button to verify the result.

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("#foo").css("background-color","yellow");});</script></head><body><h1>jQuery #id Selector</h1><p id="foo">This is foo p tag</p><span id="bar">This is bar span tag</span><div id="bill">This is bill div tag</div></body></html>

    The .class Selector

    The jQuery .class selector selects HTML element(s) based on the element class attribute. Following is a simple syntax of a .class selector:

    $(document).ready(function(){$(".class of the element")});

    Because a class can be assigned to multiple HTML elements with in an HTML document, so it is very much possible to find out multiple elements with a single .class selector statement.

    Examples

    Following is an example to select all the elements whose class is foo and change the background color of those elements. You can also change the code to use different element class name as selector and then click the icon run button to verify the result.

    <!doctype html><html><head><title>The jQuery Example</title><script src ="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$(".foo").css("background-color","yellow");});</script></head><body><h1>jQuery .class Selector</h1><p class="foo">This is foo p tag</p><p class="foo">This is one more foo p tag</p><span class="bar">This is bar span tag</span><div class="bill">This is bill div tag</div></body></html>

    So far we have covered only three standard jQuery Selectors. For a complete detail of all these jQuery selectors, you can go to through jQuery Selectors Reference.

  •  Syntax

    jQuery is used to select any HTML element from an HTML document and then perform any action on that selected element. To select an HTML element, jQuery selectors are used, we will study these selectors in detail in the next chapter. For now let’s have a look of basic jQuery Syntax to Find out or to Select or to Query an element and then perform an action on the selected element.

    Document Ready Event

    Before we look into jQuery Syntax, let’s try to understand what is Document Ready Event. Actually, before we execute any jQuery statement, we would like to wait for the document to be fully loaded. This is because jQuery works on DOM and if complete DOM is not available before executing jQuery statements, then we will not get desired result.

    Following is basic syntax of a Document Ready Event:

    $(document).ready(function(){// jQuery code goes here...});

    Alternatively you can also use the following syntax for document ready event:

    $(function(){// jQuery code goes here...});

    You should always keep Document Ready Event block inside <script>…</script> tags and you can keep this script tag either inside the <head>…</head> tags or at the bottom of the page before closing <body> tag.

    You can use either of these two syntax to keep your jQuery code inside the block which will be executed only when complete DOM is downloaded and ready to be parses.

    jQuery Syntax

    Following is the basic syntax for selecting HTML elements and then performing some action on the selected element(s):

    $(document).ready(function(){$(selector).action()});

    Any jQuery statement starts with a dollar sign $ and then we put a selector inside the braces (). This syntax $(selector) is enough to return the selected HTML elements, but if you have to perform any action on the selected element(s) then action() part is required.

    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 $().

    Examples

    Below are few examples to illustrate the basic jQuery Syntax. Following example will select all the <p> elements from an HTML document and will hide those elements. Try to click the icon run button to run the following jQuery code:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("p").hide()});</script></head><body><h1>jQuery Basic Syntax</h1><p>This is p tag</p><p>This is another p tag</p><span>This is span tag</span><div>This is div tag</div></body></html>

    Let’s re-write the above example using jQuery() method instead of $():

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){jQuery("p").hide()});</script></head><body><h1>jQuery Basic Syntax</h1><p>This is p tag</p><p>This is another p tag</p><span>This is span tag</span><div>This is div tag</div></body></html>

    Following is the jQuery Syntax to change the color of all the <h1> elements to red. Try to click the icon run button to run the following jQuery code:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$("h1").css("color","red")});</script></head><body><h1>jQuery Basic Syntax</h1><p>This is p tag</p><span>This is span tag</span><div>This is div tag</div></body></html>

    Similar way you can change the color of all the elements whose class is “red”. Try to click the icon run button to run the following jQuery code:

    <!doctype html><html><head><title>The jQuery Example</title><script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script><script>$(document).ready(function(){$(".red").css("color","red")});</script></head><body><h1>jQuery Basic Syntax</h1><p>This is p tag</p><span>This is span tag</span><div class="red">This is div tag</div></body></html>

    So far, we have seen you very basic examples of jQuery Syntax to give you clear understanding on how exactly jQuery is going to work on an HTML document. You can modify the code given in the above boxes and then try to run these programs to see them live in action.

  • Basics

    Before we start learning about jQuery Syntax, let’s have a quick look on basic concepts of Javascript. This is because, jQuery is a framework built using JavaScript capabilities. So while doing in jQuery, you can use all the functions and other capabilities available in JavaScript. So let’s quickly have a look at the most basic concepts but the most frequently used in jQuery.

    String

    A string in JavaScript (jQuery) 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 (jQuery) 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// truefalse// false0// false1// true""// false"hello"// true

    Objects

    JavaScript (jQuery) 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 (jQuery) can be either named or anonymous. A named function can be defined using function keyword as follows −

    functionnamed(){// 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.

    varhandler=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 (jQuery) variable arguments is a kind of array which has length property. Following example explains it very well −

    functionfunc(x){
       console.log(typeof x, arguments.length);}func();//==> "undefined", 0func(1);//==> "number", 1func("1","2","3");//==> "string", 3

    The arguments object also has a callee property, which refers to the function you’re inside of. For example −

    functionfunc(){return arguments.callee;}func();// ==> func

    Context

    JavaScript (jQuery) 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.

    functionscope(){
       console.log(this, arguments.length);}scope()// window, 0scope.call("foobar",[1,2]);//==> "foobar", 1scope.apply("foobar",[1,2]);//==> "foobar", 2

    Scope

    The scope of a variable is the region of your program in which it is defined. JavaScript (jQuery) 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 variablefunction(){var myVar ="local";// ==> Declare a local variable
       document.write(myVar);// ==> local}

    Callback

    A callback is a plain JavaScript (jQuery) 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

    JavaScript (jQuery) 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 −

    functioncreate(){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 setArrayvar proxied = jQuery.fn.setArray;
    
       jQuery.fn.setArray=function(){
    
      console.log(this, arguments);returnproxied.apply(this, arguments);};})();</pre>

    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 −

    Sr.No.Method & Description
    1charAt()Returns the character at the specified index.
    2concat()Combines the text of two strings and returns a new string.
    3forEach()Calls a function for each element in the array.
    4indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
    5length()Returns the length of the string.
    6pop()Removes the last element from an array and returns that element.
    7push()Adds one or more elements to the end of an array and returns the new length of the array.
    8reverse()Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
    9sort()Sorts the elements of an array.
    10substr()Returns the characters in a string beginning at the specified location through the specified number of characters.
    11toLowerCase()Returns the calling string value converted to lower case.
    12toString()Returns the string representation of the number's value.
    13toUpperCase()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. Try to click the icon run button to run the following jQuery code −

    <html><head><title>The DOM Example</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.

    While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial.