Wednesday, April 10, 2013

Dynamically adding new HTML elements using jquery

There are times, where we need to add a new html elements in client-side using javascript or jquery. Adding a new html element using javascript requires more steps to do. If there is any ready available javascripts functions, then it will be very easy to use.

Here is the javascript function for append new element to the specified target location.

function addElement(tagType, target, parameters) {
        //Create element
        if (typeof tagType != 'undefined')
           var newElement = document.createElement(tagType);

        //Add parameters
        if (typeof newElement != 'undefined') {
            if (typeof parameters != 'undefined') {
                for (parameterName in parameters) {
                    newElement.setAttribute(parameterName, parameters[parameterName]);
                }
            }
        }
        //Append element to target
        if (typeof target != 'undefined') {
            if (document.getElementById(target) != null)
                document.getElementById(target).appendChild(newElement);
        }

        return newElement;
  }

Here is the sample to use the above function

 addElement('input', "maincontent", {
            'id': 'newElementId',
            'name': 'newElementName',
            'type': 'text',
            'value': 'javascript',
            'size': '15'
        });

The above javascript sample can be changed as jquery plugin.

Here is the jquery plugin for append new element to the target.

 $.fn.appendNewElement = function addElement(tagType, parameters) {
            //Create element
            if (typeof tagType != 'undefined')
                var newElement = document.createElement(tagType);

            //Add parameters
            if (typeof newElement != 'undefined') {
                if (typeof parameters != 'undefined') {
                    for (parameterName in parameters) {
                        newElement.setAttribute(parameterName, parameters[parameterName]);
                    }
                }
            }

            //Append element to target
            $(this).append(newElement);

            return newElement;
        }

Here is the sample to use the above jquery plugin

$('#maincontent').appendNewElement('input', {
            'id': 'newElementId',
            'name': 'newElementId',
            'type': 'text',
            'value': 'jquery',
            'size': '15'
        });

 Here is the sample, which uses the above plugins