JavaScript Operations Dom Common API summary

Source: Internet
Author: User
Tags tag name

JavaScript Operations Dom Common API summary

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

Type
  • node Type (ELEMENT_NODE:1 ATTRIBUTE_NODE:2 TEXT_NODE:3 COMMENT_NODE:8``DOCUMENT_NODE:9 DOCUMENT_FRAGMENT_NODE:11)
  • node-created (createElement createTextNode cloneNode createDocumentFragment)
  • Page Modified Type (appendChild insertBefore removeChild replaceChild)
  • node Query type (document.getElementById document.getElementsByTagName``document.getElementsByName document.getElementsByClassName ``document.querySelector document.querySelectorAll)
  • node Relationship type ( )
    1. Parent relationship type ( parentNode )
    2. Brother Relationship ( previousSibling previousElementSibling nextSibling nextElementSibling )
    3. Sub-relational ( childNodes children firstNode lastNode hasChildNodes )
    4. Element attribute type ( setAttribute getAttribute )
    5. Element style type ( window.getComputedStyle getBoundingClientRect )
One, node type

Node has a property nodetype that represents the type of node, which is an integer whose value represents the corresponding node type, as follows:

    1. Node.element_node:1
    2. Node.attribute_node:2
    3. Node.text_node:3
    4. Node.cdata_section_node:4
    5. Node.entity_reference_node:5
    6. Node.entity_node:6
    7. Node.processing_instruction_node:7
    8. Node.comment_node:8
    9. Node.document_node:9
    10. Node.document_type_node:10
    11. Node.document_fragment_node:11
    12. Node.notation_node:12

Suppose we want to judge if a node is an element, and we can judge that.

if(someNode.nodeType == 1){    console.log("Node is a element");}
1.1 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:

    • NodeType is 1
    • NodeName is the element tag name, and TagName is also the return label signature
    • NodeValue is null
    • ParentNode may be document or element
    • Child nodes may be element,text,comment,processing_instruction,cdatasection or EntityReference
1.2 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:

    • NodeType is 3
    • NodeName to #text
    • NodeValue as text content
    • ParentNode is an element
    • No child nodes
1.3 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:

    • NodeType value is 2
    • NodeName is the name of the attribute
    • NodeValue is the value of the attribute
    • ParentNode is null
1.4 Comment Type

Comment Represents a comment in an HTML document, and it has several characteristics:

    • NodeType is 8
    • NodeName to #comment
    • NodeValue the contents of a comment
    • ParentNode may be document or element
    • No child nodes
1.5 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:

    • NodeType is 9
    • NodeName to #document
    • NodeValue is null
    • ParentNode is null
    • A child node may be a DocumentType or element
1.6 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:

    • NodeType is 11
    • NodeName to #document-fragment
    • NodeValue is null
    • ParentNode is null
Two, node creation type 2.1 createelement

Note: IE8 the following browsers do not support custom labels.

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.

2.2 createTextNode

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

var textNode = document.createTextNode("一个TextNode");
2.3 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:

var parent = document.getElementById("parentElement"); var parent2 = parent.cloneNode(true);// 传入trueparent2.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.
Example:

<div id="parent">    我是父元素的文本    <br/>    <span>        我是子元素    </span></div><button id="btnCopy">复制</button>var parent = document.getElementById("parent");document.getElementById("btnCopy").onclick = function(){    var parent2 = parent.cloneNode(true);    parent2.id = "parent2";    document.body.appendChild(parent2);}

Binds a button event, which copies a parent, modifies its ID, and then adds it 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 invocation of the received bool parameter is best passed in, if the parameter is not passed in, different browsers may treat their default values differently

We also 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:
* The replica node will not bind the event if it is bound by addeventlistener or for example onclick
* In the case of inline binding such as

<div onclick="showParent()"></div>

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

2.4 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

<ul id="list"></ul><input type="button" value="添加多项" id="btnAdd" />document.getElementById("btnAdd").onclick = function(){    var list = document.getElementById("list");    for(var i = 0;i < 100; i++){        var li = document.createElement("li");        li.textContent = i;        list.appendChild(li);    }}

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:

document.getElementById("btnAdd").onclick = function(){    var list = document.getElementById("list");     var fragment = document.createDocumentFragment();    for(var i = 0;i < 100; i++){      var li = document.createElement("li");        li.textContent = i;        fragment.appendChild(li);    }    list.appendChild(fragment);}

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.

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. Use Createdocumentfragment to troubleshoot performance issues when adding a large number of nodes

Third, the page modified type 3.1 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:

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 is equivalent to moving the node to another place, and if the child is bound to an event and is moved, it is still bound to the event

<div id="child">    要被添加的节点</div><br/><br/><br/><div id="parent">    要移动的位置</div>      <input id="btnMove" type="button" value="移动节点" />document.getElementById("btnMove").onclick = function(){    var child = document.getElementById("child");    document.getElementById("parent").appendChild(child);}

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.

3.2 InsertBefore

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

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
Example

<div id="parent">    父节点    <div id="child">                        子元素    </div></div><input type="button" id="insertNode" value="插入节点" />var parent = document.getElementById("parent");var child = document.getElementById("child");document.getElementById("insertNode").onclick = function(){    var newNode = document.createElement("div");    newNode.textContent = "新节点"    parent.insertBefore(newNode,child);}

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 adds the node to the end of the child element

3.3 RemoveChild

RemoveChild Delete the specified child node and return it with the following usage:

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:

if(node.parentNode){    node.parentNode.removeChild(node);}

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

3.4 ReplaceChild

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

parent.replaceChild(newChild,oldChild);

Newchild is a replacement node, either a new node or a node on a page, or a node on a page that is moved to a new location oldchild is the node that is 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 location 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.

Four, node query type 4.1 document.getElementById

There are a few points to note:
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 an 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 is not found

4.2 document.getElementsByTagName

This interface gets the element based on the element tag name, returning an immediate htmlcollection type

<div>div1</div><div>div2</div>       <input type="button" value="显示数量" id="btnShowCount"/><input type="button" value="新增div" id="btnAddDiv"/> var divList = document.getElementsByTagName("div");document.getElementById("btnAddDiv").onclick = function(){    var div = document.createElement("div");    div.textContent ="div" + (divList.length+1);    document.body.appendChild(div);}document.getElementById("btnShowCount").onclick = function(){        alert(divList.length);}

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's best to cache its length, because each loop calculates the length and is temporarily cached to improve efficiency
2. If the specified label is not present, the interface returns not NULL, but an empty htmlcollection
3. "*" means all labels

4.3 document.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 always changing
2. In HTML elements, not all elements have a name attribute, such as a div without a name attribute, 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

4.4 Document.document.getElementsByClassName

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

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

var elements = document.getElementsByClassName("test1 test2");
4.5 Document.queryselector

Find elements with CSS selectors
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.

<div>    <div>        <span class="test">第三级的span</span>      </div></div><div class="test">              同级的第二个div</div><input type="button" id="btnGet" value="获取test元素" />document.getElementById("btnGet").addEventListener("click",function(){    var element = document.querySelector(".test");    alert(element.textContent);})

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.

4.6 Document.queryselectorall

Find elements with CSS selectors
Document.queryselectorall returns all matching elements, and can match multiple selectors

<div class="test">    class为test</div><div id="test">    id为test</div><input id="btnShow" type="button" value="显示内容" />document.getElementById("btnShow").addEventListener("click",function(){    var elements = document.querySelectorAll("#test,.test");        for(var i = 0,length = elements.length;i<length;i++){        alert(elements[i].textContent);    }   })

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. Returns a non-immediate nodelist, which means that the result does not change as the document tree changes
3. Queryselector and Queryselectorall are not supported in browsers below IE8.

V. Node relationship Type 5.1 parent relationship type
    • 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, which differs from parentnode in that its parent node must be an element and, if not, returns null
5.2 Sibling Relationship Type
    • 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
      To return to the previous element node, the previous node must be element, note that the following browsers do not support IE9.
    • NextSibling
      The next node of a 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
      After returning an element node, the latter node must be element, note that the following browsers do not support IE9.
5.3 Sub-relational
    • 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 if a child node is included.
5.4 element attribute type 5.4.1 Setattribut

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

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

element.setAttribute("id","test");element.id = "test";
5.4.2 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:

var value = element.getAttribute("id");
5.5-element style 5.5.1 window.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:

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

5.5.2 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:

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 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.