To create tags dynamically:
Traditional methods: Document.Write, InnerHTML
Document.Write: The method can easily and quickly insert the string into the document, but the disadvantage is that it violates the principle that "behavior should be separated from performance". Even if you move the document.write statement to an external function, you still need to use the <script> tag in the <body> section of the tag to invoke that function. Avoid using <script> tags in the <body> section to avoid document.write methods.
InnerHTML: Used to read and write HTML content in a given element.
<div id= "Text" ><p>this is <em>my</em>content.</p></div>
ELEMENT node
<p>this is <em>my</em>content.</p> |
Html
In terms of the innerHTML attribute, there is only one HTML string with a value of <p>this is <em>my</em>content.</p> in the tag with ID text.
The innerHTML property is an HTML-specific property and cannot be used in any other markup language document.
Dom methods: createelement, AppendChild, createTextNode
CreateElement: Creates an element node, syntax: Document.createelement (nodeName) eg:document.createElement ("P"), and creates a P element.
AppendChild: Insert node, syntax: Parent.appendchild (Child)
createTextNode: Create text node, syntax: document.createTextNode (text) eg:document.createTextNode ("Hello world!"); A text node with the content "Hello world" is created.
InsertBefore: Insert a new element in front of an existing element, when calling this method, you must know three things: 1, new element: The element you want to insert (newelement) 2, Target element: Before which element (targetelement) you want to insert this new element 3, parent element: The parent element of the target element (parentelement) Syntax: Patentelement.insertbefore (newelement,targetelement) We don't have to figure out what the parent element is, because the ParentNode attribute value of the targetelement element is it. Attribute nodes and child elements of text nodes are not allowed to be element nodes
Insert a new element after the existing element: there is no such method in the DOM, but we can write this function
function InsertAfter (newelement,targetelement) { var parent=Targetelement.parentnode; if (parent.lastchild==targetelement) { parent.appendchild (newelement); } Else { parent.insertbefore (newelement,targetelement.nextsibling); }}
NextSibling: The next node of the same layer, the next sibling node
Read "JavaScript DOM Programming Art (2nd edition)" Note 7