JavaScript manipulating DOM nodes

Source: Internet
Author: User
Tags tag name

Basic concepts

Before explaining the API for manipulating the DOM, let's review some basic concepts that are key to mastering the API and must be understood.

Node type

The DOM1 class defines a node interface that is implemented by all node types in the DOM. This node interface is implemented as a node type in JS. This type cannot be accessed in the following versions of IE9, all nodes in JS inherit from node type and share the same basic properties and methods.
Node has a property nodetype that represents the type of node, which is an integer whose value represents the corresponding node type, as follows:
Node.element_node:1
Node.attribute_node:2
Node.text_node:3
Node.cdata_section_node:4
Node.entity_reference_node:5
Node.entity_node:6
Node.processing_instruction_node:7
Node.comment_node:8
Node.document_node:9
Node.document_type_node:10
Node.document_fragment_node:11
Node.notation_node:12
Suppose we want to judge if a node is an element, and we can judge that.

1 if (Somenode.nodetype = = 1) {2     console.log ("Node is a Element"); 3}

Of these node types, the most common ones we use are the element,text,attribute,comment,document,document_fragment types.
Let's take a brief look at some of these types:

Element type

element provides access to tag names, child nodes, and attributes, and the tags that we use for HTML elements such as Div,span,a are one of the elements. Element has several features:
(1) NodeType is 1
(2) NodeName is the element tag name, TagName is also the return label signature
(3) NodeValue is null
(4) ParentNode may be document or element
(5) Child nodes may be element,text,comment,processing_instruction,cdatasection or EntityReference

Text type

Text represents a textual node that contains plain text content and cannot contain HTML code, but can contain escaped HTML code. Text has the following characteristics:
(1) NodeType is 3
(2) NodeName for #text
(3) NodeValue for text content
(4) ParentNode is an element
(5) No child nodes

attr type

The attr type represents the attribute of the element, which is the node in the attributes attribute of the element, which has the following characteristics:
(1) NodeType value is 2
(2) NodeName is the name of the attribute
(3) NodeValue is the value of the attribute
(4) ParentNode is null

Comment Type

Comment Represents a comment in an HTML document, and it has several characteristics:
(1) NodeType is 8
(2) NodeName for #comment
(3) Contents of NodeValue as comments
(4) ParentNode may be document or element
(5) No child nodes

Document

Document represents the documents, in the browser, the paper object is an instance of HTMLDocument, representing the entire page, which is also a property of the Window object. Document has the following features:
(1) NodeType is 9
(2) NodeName for #document
(3) NodeValue is null
(4) ParentNode is null
(5) A child node may be a DocumentType or element

DocumentFragment type

DocumentFragment is the only type in all nodes that does not have a corresponding tag, which represents a lightweight document that may be used as a temporary repository to hold nodes that might be added to the document. DocumentFragment has the following features:
(1) NodeType is 11
(2) NodeName for #document-fragment
(3) NodeValue is null
(4) ParentNode is null

We briefly describe several common node types, and remember that the nodes in the HTML do not just include the element nodes, but also include text nodes, annotation nodes, and so on. Here we simply explain a few common nodes, students who want to further study can find out the relevant information.

Node-creation API

Here, I will use the common DOM operations API to classify, the first is to introduce the creation of the API. This type of API, in short, is used to create nodes.

CreateElement

CreateElement creates an element by passing in a specified tag name, and if the incoming label name is an unknown, a custom label is created, note: IE8 the following browsers do not support custom labels.
Use the following:

var div = document.createelement ("div");

Use createelement Note: Elements created through createelement are not part of an HTML document, but are created and not added to an HTML document. To call a method such as AppendChild or insertbefore, add it to the HTML document tree.

createTextNode

createTextNode is used to create a text node with the following usage:

1 var textnode = document.createTextNode ("one Textnode");

createTextNode receives a parameter, which is the text in the text node, like CreateElement, the created text node is just a separate node, and it also needs to be appendchild to add it to the HTML document tree

CloneNode

CloneNode is a copy of the node that is used to return the calling method, which receives a bool parameter to indicate whether to copy the child elements, using the following:

1 var parent = document.getElementById ("parentelement"); 2 var parent2 = Parent.clonenode (TRUE);//incoming True3 parent2.id = "Parent2";

This code copies a copy of the parent element through CloneNode, where the parameter of CloneNode is true, indicating that the child node of the parent is also copied and, if passed false, that only the parent node is replicated.
Let's see this.

1 <div id= "parent" > 2     I am the text of the parent element 3     <br/> 4     <span> 5         I am a child element 6     </span> 7 </ Div> 8 <button id= "btncopy" > Copy </button> 9 var parent = document.getElementById ("parent"); 11 document.getElementById ("Btncopy"). onclick = function () {     var parent2 = Parent.clonenode (true);     Parent2.id = "Parent2";     document.body.appendChild (Parent2); 15}

This code is very simple, mainly binding button events, the event content is to copy a parent, modify its ID, and then add to the document.
Here are a few things to note:
(1) Like createelement, the node created by CloneNode is simply a node that is free of HTML documents, and calls the AppendChild method to be added to the document tree
(2) If the copied element has an ID, its copy will also contain the ID, because the ID is unique, so you must modify its ID after the node is copied
(3) The call to receive the BOOL parameter is best passed in, if the parameter is not passed in, different browsers will handle their default values may be different

In addition, we have a point to note:
If the replicated node is bound to an event, will the copy also bind the event? Here is a discussion of the situation:
(1) The replica node does not bind the event if it is bound by a addeventlistener or, for example, the onclick
(2) in the case of inline binding such as

1 <div onclick= "showparent ()" ></div>

In this case, the replica node will also trigger the event.

Createdocumentfragment

The Createdocumentfragment method is used to create a documentfragment. In front of us, we said that DocumentFragment represents a lightweight document that is primarily intended to store temporary nodes that are ready to be added to the document.
The Createdocumentfragment method is primarily used when adding a large number of nodes into a document. Suppose you want to loop a set of data and then create multiple nodes to add to the document, such as

1 <ul id= "list" ></ul> 2 <input type= "button" value= "Add multiple" id= "Btnadd"/> 3  4 document.getElementById ("Btnadd"). onclick = function () {5     var list = document.getElementById ("list"); 6 for     ( var i = 0;i < 100; i++) {7         var li = document.createelement ("Li"), 8         li.textcontent = i, 9         list.appendchild (LI),     }11}

This code binds the button to an event that creates 100 Li nodes and then adds them to the HTML document in turn. This has a drawback: each time a new element is created and then added to the document tree, this process causes the browser to reflow. The so-called reflow simply means that the element size and position are recalculated, and if too many elements are added, it can cause performance problems. This is the time to use Createdocumentfragment.
DocumentFragment is not part of the document tree, it is stored in memory, so it does not cause reflow problems. We modify the above code as follows:

1 document.getElementById ("Btnadd"). onclick = function () {2     var list = document.getElementById ("list");     3     var fragment = Document.createdocumentfragment (); 4  5 for     (var i = 0;i < i++) {6       var li = documen T.createelement ("Li"); 7         li.textcontent = i; 8         Fragment.appendchild (LI), 9     }10     list.appendchild (fragment); 12}

The optimized code is mainly to create a fragment, each time the generated Li node is added to the fragment, and finally added to the list at once, you can see

Create API Summary

The creation API mainly includes the Createelement,createtextnode,clonenode and Createdocumentfragment four methods, the following points need to be noted:
(1) The node they create is an isolated node that is added to the document via AppendChild
(2) CloneNode to note if the replicated node contains child nodes and event bindings.
(3) using Createdocumentfragment to resolve performance issues when adding a large number of nodes

Page-Modified API

Before we mentioned the creation API, they simply created the node and did not actually modify the content of the page, but instead called appendchild to add it to the document tree. I'm going to classify this kind of changes to the page content here.
The API to modify page content includes: Appendchild,insertbefore,removechild,replacechild.

AppendChild

AppendChild we have used many times before, that is, adding the specified node to the end of the child element of the node that called the method. The calling method is as follows:

1 parent.appendchild (child);

The child node will act as the last node of the parent node.
AppendChild This method is very simple, but there is a point to note: If the added node is a node that exists on a page, then the node will be added to the specified location, the original location will remove the node, that is, there will not be two nodes on the page, It's equivalent to moving the node to another place. Let's see.

1 <div id= "Child" > 2     nodes to be added 3 </div> 4 <br/> 5 <br/> 6 <br/> 7 <div id= "Parent" > 8     position to move 9 </div>        <input id= "btnmove" type= "button" value= "Mobile node"/>11 document.getElementById ("Btnmove"). onclick = function () {$     var child = document.getElementById ("child");     document.getElementById ("parent"). AppendChild (child); 15}

This code is mainly to get the child node on the page, and then add to the specified location, you can see the original child node is moved to the parent.
Here's another point to note: If a child is bound to an event and is moved, it is still bound to the event.

InsertBefore

InsertBefore used to add a node to a reference node, use the following:

1 Parentnode.insertbefore (Newnode,refnode);

ParentNode represents the parent node after the new node is added
NewNode represents the node to be added
Refnode represents the reference node, before the new node is added to the node
Let's see this.

1 <div id= "parent" > 2     parent node 3     <div id= "Child" >                 4         sub-element 5     </div> 6 </div> 7 < Input type= "button" id= "Insertnode" value= "Insert Node"/> 8  9 var parent = document.getElementById ("parent"); ten var chil D = document.getElementById ("Child"), document.getElementById ("Insertnode"). onclick = function () {     var NewNode = document.createelement ("div"),     newnode.textcontent = "New Node"     Parent.insertbefore (newnode,child ); 15}

This code creates a new node and then adds it to the child node.
As with AppendChild, if the inserted node is a node on the page, the node is moved to the specified location and the event it binds is preserved.

There are a few points to note about the second parameter reference node:
(1) Refnode is a must pass, if not pass the parameter will be an error
(2) If refnode is undefined or null, InsertBefore will add the node to the end of the child element

RemoveChild

RemoveChild, as the name implies, is to delete the specified child node and return it, using the following:

1 var deletedchild = parent.removechild (node);

Deletedchild points to the deleted node's reference, which equals node, the deleted node still exists in memory and can be used for next steps.
Note: If the deleted node is not its child node, the program will error. We can make sure that we can delete it in the following way:

1 if (Node.parentnode) {2     node.parentNode.removeChild (node); 3}

Gets the parent node of the node itself through the node, and then deletes itself.

ReplaceChild

ReplaceChild is used to replace another node with one node, using the following

1 Parent.replacechild (Newchild,oldchild);

Newchild is a replacement node, which can be a new node or a node on a page, and if it is a node on a page, it will be moved to a new location
Oldchild is the node that is being replaced

Page-Modified API Summary

Page Modification API is mainly these four interfaces, to pay attention to a few features:
(1) Whether it is a new or replacement node, if the new or replaced node is originally present on the page, then the node of its original position will be removed, that is, the same node cannot exist in multiple locations on the page
(2) Events bound by the node itself will not disappear and will remain.

Node Query-type API

The node query API is also a very common API, so let's explain the use of each API separately.

document.getElementById

This interface is simple, returns an element based on the element ID, the return value is an element type, and returns null if the element does not exist.
There are a few things to note about using this interface:
(1) The ID of the element is case sensitive, be sure to write the ID of the element
(2) There may be multiple elements with the same ID in the HTML document, the first element is returned
(3) Search elements only from the document, if an element is created and an ID is specified but not added to the document, the element will not be found.

document.getElementsByTagName

This interface gets the element according to the element tag name, returns an immediate htmlcollection type, what is the instant htmlcollection type? Let's see this.

1 <div>div1</div> 2 <div>div2</div> 3  4 <input type= "button" value= "Display Quantity" id= " Btnshowcount "/> 5 <input type=" button "value=" New div "id=" btnadddiv "/>     6  7 var divlist = document.getElementsByTagName ("div"); 8 document.getElementById ("Btnadddiv"). onclick = function () {9     var div = document.createelement ("div");     div.textcontent = "div" + (divlist.length+1);     Document.body.appendChild (div);}13 document.getElementById ( "Btnshowcount"). onclick = function () {         alert (divlist.length); 16}

There are two buttons in this code, one to display the number of htmlcollection elements, and the other to add a div tag to the document. The Htmlcollcetion element mentioned earlier indicates that the collection is changed at any time, that is, there are several div in the document, it will change at any time, when we add a div and then visit htmlcollection, we will include this new Div.
There are a few things to note about using the document.getElementsByTagName method:
(1) If you want to cycle through the Htmlcollection collection, it is best to cache its length, because each cycle will calculate the length, and temporarily cache it to improve efficiency.
(2) If the specified label is not present, the interface returns not NULL, but an empty htmlcollection
(3) "*" means all labels

Document.getelementsbyname

Getelementsbyname is primarily obtained by specifying the Name property, which returns an immediate NodeList object.
The main points to note when using this interface are:
(1) The return object is an instant nodelist, which is changeable at any time
(2) In HTML elements, not all elements have a name attribute, such as a DIV does not have a Name property, but if you force the Name property of the Div, it can be found.
(3) in IE, if the ID is set to a value, and then passed in the Getelementsbyname parameter value and the ID value, then this element will be found, so it is best not to set the same value to the ID and name

Document.getelementsbyclassname

This API returns an immediate htmlcollection based on the class of the element, with the following usage

1 var elements = document.getelementsbyclassname (names);

This interface has the following points to note:
(1) The return result is an instant htmlcollection that changes according to the document structure at any time
(2) IE9 The following browsers do not support
(3) If you want to get more than 2 classname, you can pass in multiple classname, each separated by a space, for example

1 var elements = document.getelementsbyclassname ("Test1 test2");
Document.queryselector and Document.queryselectorall

These two APIs are very similar, using CSS selectors to find elements, and note that selectors conform to the rules of the CSS selector.
First, let's introduce Document.queryselector.
Document.queryselector returns the first matching element, or null if there are no matching elements.
Note that because the first matching element is returned, this API uses the depth-first search to get the element. Let's look at this example:

1 <div> 2     <div> 3         <span class= "Test" > Third-level span</span>     4     </div> 5 </ Div> 6 <div class= "Test" >             7     sibling Second Div 8 </div> 9 <input type= "button" id= "Btnget" value= " Gets the test element "/>10 document.getElementById (" Btnget "). AddEventListener (" click ", Function () {     var element = Document.queryselector (". Test");     alert (element.textcontent); 14})

This example is simple, that is, the two class contains the "test" element, one in front of the document tree, but it is in the third level, the other behind the document tree, but it is at the first level, through the queryselector get the element, it through the depth first search, Get the third level element in front of the document tree.

The difference between document.queryselectorall is that it returns all matching elements and can match multiple selectors, so let's take a look at the following example

1 <div class= "Test" > 2     Class Test 3 </div> 4 <div id= "Test" > 5     ID Test 6 </div> 7 <inpu T id= "btnshow" type= "button" value= "Show content"/> 8  9 document.getElementById ("Btnshow"). AddEventListener ("click", function () {ten     var elements = Document.queryselectorall ("#test,. Test");    One for     (var i = 0,length = elements.length;i<length;i++) {         alert (elements[i].textcontent);    14})

This code, through Queryselectorall, selects two elements using the ID selector and the class selector, and sequentially outputs its contents. Two points to note:
(1) Queryselectorall is also through depth-first search, the order of the elements searched is independent of the order of selectors
(2) A non-instantaneous nodelist is returned, which means that the result does not change as the document tree changes

Compatibility issues: Queryselector and Queryselectorall are not supported in browsers below IE8.

Node-Relational API

The relationship between each node in the HTML document can be thought of as a family tree relationship, including parent-child relationships, sibling relationships, and so on, so let's look at each of these relationships in turn.

Parent-Relational API

ParentNode: Each node has a ParentNode property that represents the parent node of the element. The parent node of element may be element,document or documentfragment.
Parentelement: Returns the parent element node of the element, unlike ParentNode, whose parent node must be an element and, if not, returns null

Brotherly Relational API

PreviousSibling: The previous node of a node, or null if the node is the first node. Note that it is possible to get a node that is a text node or note node that does not match the expected, to be processed.
Previouselementsibling: Returns the previous element node, the previous node must be element, note IE9 The following browsers are not supported.

NextSibling: The next node of the node, or null if the node is the last node. Note that it is possible to get a node that is a text node that does not match the expected, to be processed.
Nextelementsibling: Returns the next element node, the latter node must be element, note IE9 The following browsers are not supported.

Sub-relational API

ChildNodes: Returns an immediate nodelist that represents the list of child nodes of the element, which may contain text nodes, annotation nodes, and so on.
Children: An instant htmlcollection, child nodes are ELEMENT,IE9 the following browsers are not supported.
Firstnode: First child node
Lastnode: Last child node
HasChildNodes method: Can be used to determine whether to include child nodes.

Element attribute type Apisetattribute

SetAttribute: Modifies the attributes of an element according to its name and value, using the following.

1 Element.setattribute (name, value);

Where name is the attribute name and value is the attribute value. If the element does not contain the attribute, the attribute is created and assigned a value.
If the element itself contains the specified attribute named attribute, you can assign a value to the world Access property, such as the following two code is equivalent:

1 Element.setattribute ("id", "Test"), 2 3 element.id = "Test";
GetAttribute

GetAttribute returns the attribute value corresponding to the specified attribute name, or null or an empty string if it does not exist. Use the following:

1 var value = Element.getattribute ("id");
Element Style Type Apiwindow.getcomputedstyle

window.getComputedStyle is used to get the style that is applied to an element, assuming that an element is not set to a height but is highly stretched by its contents, and that the height of the getComputedStyle is used as follows:

1 var style = window.getComputedStyle (element[, Pseudoelt]);

Element is a pseudoelt that specifies a pseudo-element to match.
The returned style is a Cssstyledeclaration object.
Style allows you to access the calculated styles of an element

Getboundingclientrect

The getboundingclientrect is used to return the size of the element and its location relative to the browser's visual window, using the following:

1 var clientrect = Element.getboundingclientrect ();

Clientrect is a Domrect object that contains Left,top,right,bottom, which is the distance from the visible window, and when the scroll position changes, their values change. In addition to IE9 the following browsers, it also contains data such as height and width of the element.

JavaScript manipulating DOM nodes

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.