Recently, due to work needs, I need to dynamically create a DOM element after clicking on an element and display it. Therefore, I wrote some related JS functions and recorded them here to make a memo:
/**//* Related functions for dynamically creating DOM elements support www.jcodecraeer.com */ /**//* Get the DOM object of a certain element @obj's ID string */ function getElement(obj) { return typeof obj=='string'?document.getElementById(obj):obj; } /**//* Get the position of an element @obj's DOM object of the element, or the ID of the element */ function getObjectPosition(obj) { obj=typeof obj==='string'?getElement(obj):obj; if(!obj) { return; } var position=''; if(obj.getBoundingClientRect) //For IEs { position=obj.getBoundingClientRect(); return {x:position.left,y:position.top}; } else if(document.getBoxObjectFor) { position=document.getBoxObjectFor(obj); return {x:position.x,y:position.y}; } else { position={x:obj.offsetLeft,y:obj.offsetTop}; var parent=obj.offsetParent; while(parent) { position.x+=obj.offsetLeft; position.y+=obj.offsetTop; parent=obj.offsetParent; } return position; } } /**//* Dynamically bind event for a DOM object @oTarget The DOM object of the bound event @sEventType The bound event name, note that the event name is not added, such as 'click' @fnHandler The bound event handler function*/ function addEventHandler(oTarget, sEventType, fnHandler) { if (oTarget.addEventListener) { oTarget.addEventListener(sEventType, fnHandler, false); } else if (oTarget.attachEvent) //for IEs { oTarget.attachEvent("on" + sEventType, fnHandler); } else { oTarget["on" + sEventType] = fnHandler; } } /**//* Remove an event from a DOM object @oTarget The DOM object of the bound event @sEventType The bound event name, note that the event name is not added, such as 'click' @fnHandler The bound event handler function*/ function removeEventHandler(oTarget,sEventType,fnHandler) { if(oTarget.removeEventListener) { oTarget.removeEventListener(sEventType,fnHandler,false) } else if(oTarget.detachEvent) //for IEs { oTarget.detachEvent(sEventType,fnHandler); } else { oTarget['on'+sEventType]=undefined; } } /**//* Create a dynamic DOM object @domParams is a JSON expression of the attributes of the created object, which has the following attributes: @parentNode The parent element to which the created object belongs (can be element ID or DOM object) @domId The ID of the created object is created @domTag The tag name of the created object, supports commonly used layout elements, such as div span, etc., but does not support special elements such as input/form, @content The created object content @otherAttributes Add other attributes except the necessary attributes for the function to be created, such as [{attrName:'style.color',attrValue:'red'}] @eventRegisters Add events to the created object, similar to arrays similar to [{eventType:'click',eventHandler:adsfasdf}] - After combination, this parameter has the following form: {parentNode:document.body,domTag:'div',content:'This is tested',otherAttributes:[{attrName:'style.color',attrValue:'red'}],eventRegisters:[{eventType:'click',eventHandler:fnHandler}]} */ function dynCreateDomObject(domParams) { if(getElement(domParams.domId)) { childNodeAction('remove',domParams.parentNode,domParams.domId); } var dynObj=document.createElement(domParams.domTag); with(dynObj) { //id can also be passed in through otherAttributes, but due to the speciality of the ID, the //JSON object is still used here, and the DOM ID attribute is attached to id=domParams.domId; innerHTML=domParams.content; //innerHTML is a DOM attribute, while id etc are element attributes, pay attention to the difference} /**//*Add attribute*/ if(null!=domParams.otherAttributes) { for(var i=0;i<domParams.otherAttributes.length;i++) { var otherAttribute =domParams.otherAttributes[i]; dynObj.setAttribute(otherAttribute.attrName,otherAttribute.attrValue); } } /**//*end Add attribute*/ /**//*add related events*/ if(null!=domParams.eventRegisters) { for(var i=0;i<domParams.eventRegisters.length;i++) { var eventRegister =domParams.eventRegisters[i]; addEventHandler(dynObj,eventRegister.eventType,eventRegister.eventHandler); } } /**//*end Add related events*/ try { childNodeAction('append',domParams.parentNode,dynObj); } catch($e) { } return dynObj; } /**//** Delete child nodes from parent node @actionType defaults to append, enter string append | remove @parentNode The DOM object of the parent node, or the ID of the parent node @childNode The DOM object of the child node was deleted or the ID of the child node was deleted */ function childNodeAction(actionType,parentNode,childNode) { if(!parentNode) {return; } parentNode=typeof parentNode==='string'?getElement(parentNode):parentNode; childNode=typeof childNode==='string'?getElement(childNode):childNode; if(!parentNode || !childNode) {return;} var action=actionType.toLowerCase(); if( null==actionType || action.length<=0 || action=='append') { action='parentNode.appendChild'; } else { action='parentNode.removeChild'; } try { eval(action)(childNode); } catch($e) { alert($e.message); } }Example of usage:
var htmlAttributes= [{attrName:'class',attrValue:'Style name'} //for IEs,{attrName:'className',attrValue:'Style name'} //for ff] var domParams={domTag:'div', content:'Div' innerHTML of dynamic div', otherAttributes:htmlAttributes}; var newHtmlDom=dynCreateDomObject(domParams);//Specify style through the form setAttribute('style','position:absolute............')// has no effect. It can only be done by the following form, jiongnewHtmlDom.style.zIndex='8888';newHtmlDom.style.position='absolute';newHtmlDom.style.left='100px';newHtmlDom.style.top='200px';newHtmlDom.style.top='200px';