Javascript crea...LOGIN

Javascript creates node

The commonly used methods for creating nodes are listed below:

QQ截图20161013111044.png

The above four methods are all methods of the document object.

createElement()

createElement() is used to create an element node, that is, a node with nodeType=1.

Syntax:

    document.createElement(tagName)

Where tagName is the name of the HTML tag and will return a node object.

For example, the statements to create <div> tags and <p> tags are as follows:

var ele_div=document.createElement("div");

var ele_p=document.createElement("p");

createTextNode()

createTextNode() is used to create a text node, that is, a node with nodeType=3 .

Syntax:

    document.createTextNode(text)


Among them, text is the content of the text node, and a node object will be returned.

For example, create a text node with the content "This is a text node":

var ele_text=document.createTextNode(" 这是文本节点 ");

createComment()

createComment() Used to create a comment node, that is, a node with nodeType=8.

Syntax:

    document.createComment(comment)

Among them, comment is the content of the comment and will return a node object.

For example, create a comment node with the content "This is a comment node":

var ele_comment=document.createComment(" 这是一个注释节点 ");

createDocumentFragment()

createDocumentFragment( ) is used to create document fragment nodes.

Document fragment node is a collection of several DOM nodes, which can include various types of nodes, such as element nodes, text nodes, comment nodes, etc. The document fragment node is empty when it is created, and nodes need to be added to it.

Syntax:

     document.createDocumentFragment();

For example, create a document fragment node and assign it to the variable:

var ele_fragment=document.createDocumentFragment();
Next Section
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> </head> <body> <script type="text/javascript"> var main1 = document.body; //创建链接 function createa(url,text) { var alink = document.createElement("a"); alink.setAttribute("href",url); alink.innerHTML=text; return alink; } // 调用函数创建链接 main1.appendChild(createa("http://ask.php.cn","php中文网")); </script> </body> </html>
submitReset Code
ChapterCourseware