add and clone HTML element by using jQuery

Sometimes you need to add one HTML element to another element. By using jQuery, you can easily do this thing.

jQuery framework provides many functions prepend(), prependTo() and clone() functions to full fill this type requirement.

 

<html>
    <head>
        <title>This is jquery example for creating the nodes dynamically</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                //prepend will insert given element at the begining of specified id
                $('#parentid').prepend('<div>This element added using prepend method</div>');
               
                //Similar to prepend(), prependTo() is used for adding DOM nodes dynamically. It inserts the specified
                //element(s) at the beginning of the selected target, where the target can be in the form of an HTML
                //element, a string, or a jQuery object. The method returns a jQuery object. The following is the equivalent
                //of the previous prepend() call.
                //$('<p>append element using prependTo method</p>').prependTo('p');
           
                 //When we want to add a DOM node (which is a copy of an existing element) on the fly, we use the clone()
                 //method. This method makes a copy of the selected element and returns it as a new jQuery object. To
                 //make a copy of the h2 element in the jQuery code and insert it before the paragraph element, the code
                //may be as follows:

               // $('div').clone().prependTo('p');           
           
            });   
        </script>    
    </head>
    <body>
        <div id="parentid">
        This is simple text before using jquery
        </div>
        <p>append element using text</p>
    </body>
</html>

 

$('#parentid').prepend('<div>This element added using prepend method</div>') will insert "<div>This element added using prepend method</div>" element at the begining of the element whose id is "parentid".

 

$('<p>append element using prependTo method</p>').prependTo('p') will insert the specified element or elements at the beginning of the selected target, where the target can be in the form of an HTML element, a string, or a jQuery object.

 

$('div').clone().prependTo('p')  will add a copy of <div> element on the fly. clone() method makes a copy of the selected element and returns it as a new jQuery object.

 

Download source code: prepend and clone.zip (36.05 kb)