Create a DOM node using JavaScript metaprogramming

Source: Internet
Author: User

When using JavaScript to create DOM nodes, document. createelement, setattribute,
Document. createtextnode and Other lengthy node operation methods with browser compatibility issues, although some people propose to use String concatenation before
Using. innerhtml = can reduce the cost of creating nodes and provide better performance. However, in my impression, innerhtml cannot meet all the requirements (I forgot the specific requirements ).
The following describes how to dynamically create a node using the Javascript metaprogramming technique.

So what is metaprogramming? Ruby on
Promote the rails (ROR) framework. The ror framework uses magic to implement simplicity and uses Ruby to implement many functions that need to be implemented in other languages. The most classic is the ROR framework.
Activerecord. Let's take a look at the following sectionCode:

Person = person. find_by_email ('xxx @ x1989.com ')
Person. Age = 23
Person. Save
The above code can be replaced with an SQL statement, as shown below:

Select * From person where email = 'xxx @ x1989.com'
Update person set age = 23 Where email = 'xxx @ x1989.com'
Even if you don't know Ruby and SQL, you can see that the ruby syntax is more natural. It is just through the meta-Programming Technique of rails that we do not needProgramUse different languages. Definition of metaprogramming:

<BLOCKQUOTE> metaprogramming refers to the compilation of a certain type of computer program. Such computer programs write or manipulate other programs (or themselves) as their data, or complete part of the work that should have been completed during compilation at runtime. </BLOCKQUOTE>

So, I want to use JavaScript to generate functions for dynamic nodes with "create _" + any HTML5 tag names, such as using create_form, create_div, and create_input to generate nodes with corresponding names, use the following API:

// ① Create a node that only contains text
// <Span> Hello World </span>
VaR span = create_span ('Hello World ');
// <Br/>
VaR BR = create_br ();

// ② Attributes can be defined with the object literal in parameter 1
// <Input type = "text" size = "20" value = "123"/>
VaR input = create_input ({
'Type': 'text ',
'SIZE': 20,
'Value': '000000'
})
// ③ Define a text node with parameter 2
// <A href = "http://www.google.com.hk" Title = "Google Search" target = "_ blank" rel = "XXXXX" costom_attr = "Custom Attributes"> Search </a>
VaR A = create_a ({
'Href ': 'http: // www.google.com.hk ',
'Title': 'Google search ',
'Target': '_ blank ',
'Rel ': 'xxxxx ',
'Costom _ attr': 'custom attribute ',
}, 'Search ');

// ④ Parameter 2 can be node parameter 3 (optional) is a text node
// <Div> This is the logo </div>
VaR DIV = create_div ({}, create_img ({'src': 'http: // www.google.com.hk/intl/zh-cn/images/logo_cn.png'}), 'This is the logo ')

// ⑤ Parameter 2 can also be an array composed of nodes
// <Ul class = "list1"> <li> Project 1 </LI> <li> Project 2 </LI> <li> Project 3 </LI> </ul>
VaR ul = create_ul ({
'Class': 'list1'
}, [Create_li ('Project 1'), create_li ('Project 2'), create_li ('Project 3')]);
Implementation Method:

Void function (){
// Supports Generating functions using dynamic nodes with "create _" + any HTML5 Tag Name
VaR Doc = Document, win = window,
// HTML5 Tag:
Tags = ["A", "abbr", "acronym", "Address", "applet", "area", "article", "aside", "audio ", "B", "base", "basefont", "BDO", "big", "BLOCKQUOTE", "body", "Br", "button", "canvas ", "caption", "center", "cite", "code", "col", "colgroup", "command", "DataGrid", "datalist", "datatemplate ", "DD", "Del", "details", "dialog", "dir", "Div", "dfn", "DL", "DT", "em ", "embed", "Event-source", "fieldset", "figure", "font", "footer", "form", "frame", "frameset ", "h1", "h2", "H3", "H4", "H5", "H6", "head", "Header", "HR", "html ", "I", "iframe", "IMG", "input", "ins", "isindex", "KBD", "label", "legend", "Li ", "Link", "M", "map", "menu", "meta", "meter", "nav", "nest", "noframes", "NoScript ", "object", "ol", "optgroup", "option", "output", "P", "Param", "pre", "progress", "Q ", "Rule", "S", "SAMP", "script", "section", "select", "small", "Source", "span", "strike ", "strong", "style", "sub", "Sup", "table", "tbody", "TD", "textarea", "tfoot", "th ", "thead", "time", "title", "TR", "TT", "U", "Ul", "Var", "video ", "XMP"];
For (VAR I = 0; tags [I]; I ++ ){
// Closure is a good stuff
Win ['create _ '+ tags [I] = function (TAG ){
Return function (attrs, childnode, textnode ){
Return createnode (TAG, attrs, childnode, textnode)
}
} (Tags [I]); Women's brand rankings
}
VaR createnode = function (tagname, attrs, childnode, textnode ){
// Create a node named after tagname
VaR node = Doc. createelement (tagname );

// Process the attrs parameter setting node attributes
Typeof attrs === 'string '? Createtextnode (node, attrs): createattributenode (node, attrs); // create and set attribute nodes
// Process the childnode parameter to add a subnode
If (typeof childnode === 'string '){
Createtextnode (node, childnode );
} Else if (childnode & childnode. nodename ){
Node. appendchild (childnode)
} Else if (childnode instanceof array ){
For (VAR I = 0; childnode [I]; I ++ ){
Node. appendchild (childnode [I])
}
}

// Process text nodes
If (textnode & typeof textnode === 'string '){
Createtextnode (node, textnode );
}
Return node;
}
VaR createattributenode = function (node, attrs ){
For (var I in attrs) {Freight Forwarders
// The following method applies to native node attributes
// Node [I] = attrs [I];
// In IE, setting setattribute to some native attributes may cause compatibility problems.
// Node. setattribute (I, attrs [I]);
// Document. createattribute native attributes in IE are set without quotation marks
VaR A = Doc. createattribute (I );
A. value = attrs [I];
Node. setattributenode ();
}
}
VaR createtextnode = function (node, text ){
Node. appendchild (Doc. createtextnode (text ))
}
}();

Related Article

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.