"repost" JavaScript Operations Dom Common API summary

Source: Internet
Author: User
Tags tag name

JavaScript Operations Dom Common API summary

Text collation of JavaScript operation of some of the Dom's common api, according to its role in order to create, modify, query and other types of api, mainly used to review the basic knowledge, deepen the understanding of native js.

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 take a look at this example

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 an example

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 basically creates a fragment, each time the generated Li node is added to the fragment, and the last one is added to the list at once, you can see the example

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 look at an example

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 take a look at this example

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.replacenode (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 take a look at this example

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, also contains the elements of the height and width and other data, specifically to see the link

Summarize

This paper mainly summarizes the API interface of Operation Dom commonly used in native js, mainly in order to review the basic Knowledge. Usually developed with more jquery class library, the basic knowledge of the understanding may gradually forgotten, but these basic knowledge is the basis of our foothold, only master the original js, can really do a good job of JS Development.

Original Address: http://luopq.com/2015/11/30/javascript-dom/

Wooden tree on the 2 floor
Good article, the senior year that part of the summary again, good
1/f ender.lu
well
done.thks

"repost" JavaScript Operations Dom Common API summary

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.