Summary of common JavaScript native DOM operation APIs

Source: Internet
Author: User
I was stuck with this question during the recent interview, so I took the time to review it. Several objects NodeNode is an interface called a node in Chinese. Many types of DOM elements inherit from it and share the same basic...



I was stuck with this question during the recent interview, so I took the time to review it.

Several objects Node

Node is an interface called a Node. Many types of DOM elements inherit from it and share the same basic attributes and methods. Common Node types include element, text, attribute, comment, and document. (pay attention to the differences between nodes and elements. An element belongs to a Node ).

Node has a property nodeType that indicates the Node type. It is an integer whose values represent the corresponding Node types, as shown below:

{ELEMENT_NODE: 1, // Element Node ATTRIBUTE_NODE: 2, // attribute node TEXT_NODE: 3, // text node DATA_SECTION_NODE: 4, metadata: 5, ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, // annotation node DOCUMENT_NODE: 9, // document DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, // document fragation_node: 12, Priority: 1, DOCUMENT_POSITION_PRECEDING: 2, DOCUMENT_POSITION_FOLLOWING: 4, DOCUMENT_POSITION_CONTAINS: 8, DOCUMENT_POSITION_CONTAINED_BY: 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32}
NodeList

The NodeList object is a collection of nodes, which are generally returned by Node. childNodes, document. getElementsByName, and document. querySelectorAll.

Note that Node. childNodes, document. the result of NodeList returned by getElementsByName is real-time (similar to HTMLCollection), while document. the results returned by querySelectorAll are fixed, which is special.

Example:

Var childNodes = document. body. childNodes; console. log (childNodes. length); // if the result is "2" document. body. appendChild (document. createElement ('P'); console. log (childNodes. length); // The output at this time is "3"
HTMLCollection

HTMLCollection is a special NodeList that represents a general set containing several elements (the element order is the order in the Document Stream). It is updated in real time, it is automatically updated when the elements it contains change. In addition, it is a pseudo Array. If you want to operate them like an Array, you need to call them like Array. prototype. slice. call (nodeList, 2.

Node search API
  • Document. getElementById: searches for elements by ID. It is case sensitive. If multiple results exist, only the first one is returned;

  • Document. getElementsByClassName: searches for elements by class name. Multiple class names are separated by spaces and an HTMLCollection is returned. Note that the compatibility is IE9 + (inclusive ). In addition, not only document, but other elements also support the getElementsByClassName method;

  • Document. getElementsByTagName: searches for elements based on tags. * queries all tags and returns an HTMLCollection.

  • Document. getElementsByName: searches for the element based on its name attribute and returns a NodeList.

  • Document. querySelector: returns a single Node, IE8 + (inclusive). If multiple results are matched, only the first one is returned.

  • Document. querySelectorAll: return a NodeList, IE8 + (inclusive ).

  • Document. forms: gets all the forms on the current page and returns an HTMLCollection;

Node creation API

The node creation API mainly includes four methods: createElement, createTextNode, cloneNode, and createDocumentFragment.

CreateElement

Creation element:

Var elem = document. createElement ("p"); elem. id = 'test'; elem. style = 'color: red'; elem. innerHTML = 'I am a newly created node'; document. body. appendChild (elem );

The element created through createElement does not belong to the document object. It is only created and not added to the html document. You must call appendChild or insertBefore to add it to the HTML document.

CreateTextNode

Create a text node:

Var node = document. createTextNode ("I Am a text node"); document. body. appendChild (node );
CloneNode

Clone a node: node. cloneNode (true/false). It receives a bool parameter to indicate whether to copy sub-elements.

var from = document.getElementById("test");var clone = from.cloneNode(true);clone.id = "test2";document.body.appendChild(clone);

The cloned node does not clone the event, unless the event is

In this way, the binding with addEventListener and node. onclick = xxx; method will not be copied.

CreateDocumentFragment

This method is used to create a DocumentFragment, that is, file fragmentation. It represents a lightweight document, mainly used to store temporary nodes. It can be used to greatly improve the performance when a large number of DOM operations are performed.

Suppose there is an existing question that requires 10000 li addresses to be added to ul. We first use the simplest concatenation string method to achieve this:

 
 
    Script (function () {var start = Date. now (); var str = ''; for (var I = 0; I <10000; I ++) {str + ='
  • Subnode '+ I +'
  • ';} Document. getElementById ('ul '). innerHTML = str; console. log ('time consumed: '+ (Date. now ()-start) + 'millisecond '); // 44 Ms}) (); script

    Change the append method one by one. Needless to say, this method is definitely inefficient:

     
     
      Script (function () {var start = Date. now (); var str = '', li; var ul = document. getElementById ('ul '); for (var I = 0; I <10000; I ++) {li = document. createElement ('lil'); li. textContent = 'subnode'; ul. appendChild (li);} console. log ('time consumed: '+ (Date. now ()-start) + 'millisecond '); // 82 Ms}) (); script

      Finally, try the document fragmentation method. It is foreseeable that this method is certainly better than the second method, but it should not be faster than the first one:

       
       
        Script (function () {var start = Date. now (); var str = '', li; var ul = document. getElementById ('ul '); var fragment = document. createDocumentFragment (); for (var I = 0; I <10000; I ++) {li = document. createElement ('lil'); li. textContent = 'subnode'; fragment. appendChild (li);} ul. appendChild (fragment); console. log ('time consumed: '+ (Date. now ()-start) + 'millisecond '); // 63 MS}) (); script
        Node modification API

        Node modification APIs all have the following features:

        1. Whether it is adding or replacing a node, if it is originally on the page, the node in the original position will be removed;

        2. After modification, events bound to the node itself will not disappear;

        AppendChild

        This is actually already used many times. The syntax is:

        parent.appendChild(child);

        It will append the child to the end of the child node of the parent. In addition, if the added node exists in a page, the node will be added to a new location after execution, and its original location will be removed from the node, that is to say, there will not be two nodes on the page at the same time, and their events will be retained.

        InsertBefore

        Insert a node to the front of another node. Syntax:

        parentNode.insertBefore(newNode, refNode);

        I personally think this API is very unreasonable, because you only need to know newNode and refNode when inserting nodes, and parentNode is redundant, so the jQuery encapsulated API is better:

        NewNode. insertBefore (refNode); // For example, $ ("p"). insertBefore ("# foo ");

        So remember not to confuse this native API with jQuery's API usage! For better understanding, here is a simple example:

        I am a parent node

        I am an old subnode

        Script var parent = document. getElementById ("parent"); var child = document. getElementById ("child"); document. getElementById ("insertNode "). addEventListener ('click', function () {var newNode = document. createElement ("p"); newNode. textContent = "I am a new node"; parent. insertBefore (newNode, child) ;}, false); script

        About the second parameter:

        • RefNode is required. If this parameter is not set, an error is returned;

        • If refNode is undefined or null, insertBefore adds the node to the end;

        RemoveChild

        RemoveChild is used to delete a specified child node and return the child node. Syntax:

        var deletedChild = parent.removeChild(node);

        DeletedChild points to the reference of the deleted node, which still exists in the memory. You can perform the next operation on it. In addition, if the deleted node is not its subnode, an error is returned. Generally, deleting nodes is like this:

        function removeNode(node){    if(!node) return;    if(node.parentNode) node.parentNode.removeChild(node);}
        ReplaceChild

        ReplaceChild is used to replace one node with another. Syntax:

        parent.replaceChild(newChild, oldChild);
        Node link API

        There are various relationships between nodes in the DOM, such as parent-child relationship and sibling relationship.

        Parent relationship API
        • ParentNode: each node has a parentNode attribute, which indicates the parent node of the element. The parent node of Element may be Element, Document or DocumentFragment;

        • ParentElement: returns the parent Element node of an Element. The difference between parentNode and parentNode is that its parent node must be an Element. If not, null is returned;

        Sub-link API
        • Children: returns a Real-Time HTMLCollection. All child nodes are elements, which is not supported by browsers earlier than IE9;

        • ChildNodes: returns a Real-Time NodeList, indicating the list of child nodes of the element. Note that the child node may contain text nodes and comment nodes;

        • FirstChild: returns the first child node. If null is not returned, a firstElementChild is returned;

        • LastChild: returns the last subnode. If null is not returned, a lastElementChild is returned;

        Sibling relational API
        • Previussibling: the previous node of the node. If it does not exist, null is returned. Note that the possible nodes are text nodes or comment nodes, which do not conform to expectations. You need to handle them.

        • NextSibling: The next node of the node. If it does not exist, null is returned. Note that it is possible that the obtained node is a text node, which is inconsistent with the expectation and must be processed.

        • Previuselementsibling: returns the previous Element Node. The previous Element must be an Element. Note that the browser below IE9 does not support this Element.

        • NextElementSibling: returns the last Element node, which must be an Element. Note that the browser below IE9 does not support this node.

        Element attribute API SetAttribute

        Set attributes for the element:

        element.setAttribute(name, value);

        Name indicates the feature name and value indicates the feature value. If the element does not contain this feature, the feature is created and assigned a value.

        GetAttribute

        GetAttribute returns the feature value corresponding to the specified feature name. If no feature value exists, null is returned:

        var value = element.getAttribute("id");
        Style APIs Directly modify the style of an element
        elem.style.color = 'red';elem.style.setProperty('font-size', '16px');elem.style.removeProperty('color');
        Dynamically add style rules
        var style = document.createElement('style');style.innerHTML = 'body{color:red} #top:hover{background-color: red;color: white;}';document.head.appendChild(style);
        Window. getComputedStyle

        You can only obtain inline styles through element. sytle. xxx. You can use window. getComputedStyle to obtain all styles applied to elements. IE8 or earlier versions do not support this method.

        var style = window.getComputedStyle(element[, pseudoElt]);
        GetBoundingClientRect

        GetBoundingClientRect is used to return the element size and its position relative to the browser's visual window. The usage is as follows:

        var clientRect = element.getBoundingClientRect();

        ClientRect is a DOMRect object that contains width, height, left, top, right, and bottom. It is relative to the top of the window rather than the top of the document, and its values change when you scroll the page.

        The above is the summary of common JavaScript native DOM operation APIs. For more information, see PHP Chinese website (www.php1.cn )!

        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.