JS dynamic method of creating DOM elements _javascript Tips

Source: Internet
Author: User
Tags tag name

The example of this article is about JS dynamic method of creating DOM elements. Share to everyone for your reference. Specifically as follows:

Recently, because of work needs, by clicking on an element, dynamically create a DOM element and display, so write some related JS functions, in this record, to make a memo:

/* The correlation function support for dynamically creating DOM elements *///* Gets the ID string of the element @obj the DOM object of an element/function getelement (obj) {return typeof obj== ' string '? Docume
Nt.getelementbyid (obj): obj; /* * Gets the position of an element @obj the DOM object of that element, or the ID/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; }///////////////-Bind the event to a DOM object to dynamically bind the event @oTarget the DOM object @sEventType the bound event name, note that the event name is not on, such as ' click ' @fnHandler the bound event handler/function add EventHandler (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 @sEventType the bound event name, and note that the event name is not on, such as ' click ' @fnHandler the bound event handler/function re Moveeventhandler (Otarget,seventtype,fnhandler) {if (Otarget.removeeventlistener) {Otarget.removeeventlistener ( Seventtype,fnhandler,false)} else if (otarget.detachevent)//for IEs {otarget.detachevent (Seventtype,fnhandl
   ER);
   else {otarget[' on ' +seventtype]=undefined; }/* Create a Dynamic DOM object @domParams is the JSON expression of the property of the object being created, which has the following properties: @parentNode the parent element (either an element ID or a DOM object) to which the object is created @domId the ID of the object being created @domTag The tag name of the created object, which supports commonly used layout elements such as Div span, but does not support special elements such as Input\form @content the content of the object being created @otherAttributes add additional attributes other than the required function for the object being created, such as [{ Attrname: ' Style.color ', AttrValue: ' Red '} @eventRegisters adding things for objects created, like an array of [{eventtype: ' click ', EVENTHANDLER:ADSFASDF}]-After being combined, the parameter has the following form: {parentnode:document.body,domtag: ' div ', Content: ' This is the test ', Otherattributes:[{attrname: ' Style.color ', AttrValue: ' Red '}],eventregisters:[{eventtype: ' click ', Eventhandler:fnhandler}]} */function Dyncreatedomobject (domparams) {if (GetElement (Domparams.domid)) {Childnodea
  Ction (' Remove ', domparams.parentnode,domparams.domid);
  } var dynobj=document.createelement (Domparams.domtag);
   The WITH (dynobj) {//id can also be passed in Otherattributes, but for the specificity of the ID, the//json object is still passed in here and Id=domparams.domid with the DOM id attribute attachment;
   Innerhtml=domparams.content; innerHTML is the DOM attribute, and the ID is the element attribute, note the difference}/* Add attribute/if (null!=domparams.otherattributes) {for (Var i=0;i<domparams.ot
    herattributes.length;i++) {var otherattribute =domparams.otherattributes[i];
   Dynobj.setattribute (Otherattribute.attrname,otherattribute.attrvalue); }/*end Add Properties/* Add related Event/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 Event/try {childnodeaction (' append ', domparams.parentnode,dynobj);
catch ($e) {} return dynobj; /* Delete child nodes from parent node @actionType default is append, input string Append | Remove @parentNode the DOM object of the parent node, or the ID of the parent node @childNode the DOM object of the deleted child node or the ID of the deleted child node/function childnodeaction (ActionType,
 Parentnode,childnode) {if (!parentnode) {return;}
 Parentnode=typeof parentnode=== ' string ' getelement (parentnode):p Arentnode;
 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);

 }
}

Use examples:

var htmlattributes=
[
{attrname: ' class ', AttrValue: ' Style name '}//for IEs
,
{attrname: ' ClassName ', AttrValue: ' Style name '}//for ff
]  
var domparams={domtag: ' Div ', content: ' Dynamic div's innerHTML ', Otherattributes: Htmlattributes};
var newhtmldom=dyncreatedomobject (domparams);
The style has no effect through the form of setattribute (' style ', ' Position:absolute .... ... ')
//, which can only be done in the following form, Jiong
newhtmldom.style.zindex= ' 8888 ';
newhtmldom.style.position= ' absolute ';
newhtmldom.style.left= ' 100px ';
newhtmldom.style.top= ' 200px ';

I hope this article will help you with your JavaScript programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.