$() and jQuery() functions are mainly used for selecting the html elements on a web page.But they have another important use as well .$() and jQuery() can be used for creating html elements dynamically.
To create an html element dynamically we pass the html for the element to this function.For example to create and add a span element this script can be used
$("<span> Welcome </span>").appendTo("body");
The above script will create a span element on the fly and appendTo() method will add the span element to the body.
If we are using jquery version 1.4 or higher ,we can pass an options object as a second parameter .So using this method overload we can write the above script as:
$("<span/>", { html: "Welcome" }).appendTo("body");
To create a button and add it to the html body dynamically we can use the following script
$("<Button/>", { html: "click", click: function () { alert("clicked"); } } ).appendTo("body");
In the above script we are setting the attributes html and click.For the click attribute we are passing an anonymous function.Instead of passing an anonymous function we can pass a named function as:
$(document).ready( function () { $("<Button/>", { html: "click", click: buttonHandler } ).appendTo("body"); }); var buttonHandler=function() { alert("clicked1"); }
Leave a Reply