Common APIs for DOM-based JavaScript operations-javascript tips-js tutorial

Source: Internet
Author: User
DOM (DocumentObjectModel) is a Document Object Model. APIs for HTML and XML documents (application interfaces) are provided ). This article introduces the common APIs for javascript operations on dom. If you are interested in javascriptdomapi, join us. Preface

DOM (Document Object Model) is a Document Object Model. It is an API (application interface) for HTML and XML documents ). DOM depicts a hierarchical node tree that allows developers to add, remove, and modify a part of a page. DOM originated from Netscape and DHTML (Dynamic HTML), founded by Microsoft, but now it has become a true cross-platform and language-neutral way of displaying and operating page tags.

Reading directory

Basic Concepts
Node creation api
Page modified API
Node query API
Node relational api
Element attribute api
Element style api

Summary

The text sorts out some common APIs for javascript operations on DOM, and organizes them into various types of Apis based on their functions, such as creation, modification, and query. These APIs are mainly used to review basic knowledge, deepen understanding of native js.

Basic Concepts

Before explaining how to operate DOM APIs, let's first review some basic concepts. These concepts are the key to understanding APIs and must be understood.

Node Type

DOM1 defines a Node interface, which 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 versions earlier than IE9. All nodes in JS inherit from the Node type and share the same basic attributes and methods.

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

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

If we want to determine whether a Node is an element, we can determine this.

 if(someNode.nodeType == ){   console.log("Node is a element"); }

Among these Node types, the most common types are element, text, attribute, comment, document, document_fragment.
Let's briefly introduce these types:

Element type

Element provides access to element tag names, subnodes, and features. tags such as p, span, and a are commonly used in HTML elements. Element has the following features:

(1) nodeType is 1
(2) nodeName indicates the element tag name, And tagName also indicates the returned tag name.
(3) nodeValue is null
(4) parentNode may be a Document or Element.
(5) The subnode may be Element, Text, Comment, Processing_Instruction, CDATASection, or EntityReference.

Text Type

Text indicates a Text node. It contains plain Text content and cannot contain html code, but can contain html code after escaping. Text has the following features:

(1) nodeType is 3
(2) nodeName is # text
(3) nodeValue is text content
(4) parentNode is an Element.
(5) No subnodes

Attr type

The Attr type indicates the characteristics of an element, which is equivalent to the node in the attributes attribute of an element. It has the following features:

(1) The value of nodeType is 2.
(2) nodeName is the feature name.
(3) nodeValue is the feature value.
(4) parentNode is null.

Comment type

Comment indicates comments in HTML documents. It has the following features:

(1) nodeType is 8
(2) nodeName is # comment
(3) nodeValue is the commented content
(4) parentNode may be a Document or Element.
(5) No subnodes

Document

Document indicates the document. In the browser, the Document object is an instance of HTMLDocument, indicating the entire page. It is also an attribute of the window object. Document has the following features:

(1) nodeType is 9
(2) nodeName is # document
(3) nodeValue is null
(4) parentNode is null.
(5) The subnode may be a DocumentType or Element.

DocumentFragment type

DocumentFragment is the only type in all nodes that does not have corresponding tags. It represents a lightweight document and may be used as a temporary repository to save nodes that may be added to the document. DocumentFragment has the following features:

(1) nodeType is 11
(2) nodeName is # document-fragment
(3) nodeValue is null
(4) parentNode is null.

We briefly introduce several common Node types. Remember that nodes in HTML not only include element nodes, but also text nodes and comment nodes. Here we just briefly describe several common nodes. If you want to learn more, you can find the relevant information.

Node creation api

Here, I will classify common DOM operation APIs. The first thing I want to introduce is the creation api. In short, this type of api is used to create nodes.

CreateElement

CreateElement creates an element by passing in a specified tag name. If the incoming tag name is unknown, a custom tag is created. Note: custom tags are not supported in browsers under IE8.

Use:

var p = document.createElement("p");

When using createElement, note that the element created through createElement does not belong to the html document, but is created and not added to the html document, you need to call methods such as appendChild or insertBefore to add them to the HTML document tree.

CreateTextNode

CreateTextNode is used to create a text node. Its usage is as follows:

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 also an independent node, and appendChild is also required to add it to the HTML document tree.

CloneNode

CloneNode is a copy of the node used to return the call method. It receives a bool parameter to indicate whether to copy sub-elements, using the following:

Var parent = document. getElementById ("parentElement"); var parent = parent. cloneNode (true); // pass in true parent. id = "parent ";

This code copies a parent element through cloneNode. The parameter cloneNode is true, indicating that the child node of the parent is also copied. If false is passed in, it indicates that only the parent node is copied.

Let's take a look at this example.

I am the text of the parent Element
I am a child element

CopyVar parent = document. getElementById ("parent"); document. getElementById ("btnCopy "). onclick = function () {var parent = parent. cloneNode (true); parent. id = "parent"; document. body. appendChild (parent );}

This code is very simple. It is mainly used to bind a button event. The event content is to copy a parent, modify its id, and add it to the document.

Note the following points:

(1) Like createElement, nodes created by cloneNode are only nodes not included in the html document. You must call the appendChild method to add the nodes to the document tree.
(2) If the copied element has an id, its copy will also contain this id. Because the id is unique, you must modify its id after the node is copied.
(3) it is best to pass in the received bool parameter. If this parameter is not passed in, different browsers may process the default values differently.

In addition, we also need to pay attention to the following points:

If the copied node is bound to an event, will the copy be bound to the event? Here we will discuss the situation as follows:

(1) If an event is bound through addEventListener or onclick, the replica node will not bind the event
(2) For inline binding, for example

 

In this way, the copy node will also trigger events.

CreateDocumentFragment
The createDocumentFragment method is used to create a DocumentFragment. As we mentioned earlier, DocumentFragment represents a lightweight document,

It is mainly used to store temporary nodes to be added to the document.
The createDocumentFragment method is used to add a large number of nodes to the document. Assume that you want to cycle a group of data and create multiple nodes to add them to the document, for example

 
 
    Document. getElementById ("btnAdd "). onclick = function () {var list = document. getElementById ("list"); for (var I =; I <; I ++) {var li = document. createElement ("li"); li. textContent = I; list. appendChild (li );}}

    This code binds the button to an event. This event creates 100 li nodes and adds them to the HTML document in sequence. This has one drawback: each time a new element is created and then added to the document tree, this process will cause the browser to flow back. The so-called reflux simply means that the element size and position will be recalculated. If too many elements are added, performance problems will occur. At this time, createDocumentFragment is used.

    DocumentFragment is not part of the document tree and is stored in the memory, so it will not cause backflow problems. The above code is modified as follows:

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

    The optimized code mainly creates a fragment. Each generated li node is first added to the fragment and then to the list at one time. You can refer to the example below.

    Summary

    The createapi mainly includes four methods: createElement, createTextNode, cloneNode, and createDocumentFragment. Pay attention to the following:

    (1) The nodes they create are only isolated nodes and must be added to the document through appendChild.
    (2) cloneNode: Check whether the copied node contains subnodes and event binding.
    (3) using createDocumentFragment to solve performance problems when adding a large number of nodes

    Page modified API

    As mentioned above, the creation APIs only create nodes and do not actually modify the page content. Instead, they call appendChild to add them to the document tree. Here I will classify this type of content that will be modified to the page as one type.

    APIS for modifying page content include appendChild, insertBefore, removeChild, and replaceChild.

    AppendChild

    AppendChild has been used multiple times before, that is, to add the specified node to the end of the child element of the node that calls this method. The call method is as follows:

    parent.appendChild(child);

    The child node is the last child node of the parent node.

    AppendChild is a simple method, but you need to note that if the added node exists in a page, the node will be added to the specified position after execution, the original location of the node will remove the node. That is to say, there will be no two nodes on the page at the same time, which is equivalent to moving the node to another place. Let's look at the example.

    Node to be added




    Location to be moved

    Document. getElementById ("btnMove "). onclick = function () {var child = document. getElementById ("child"); document. getElementById ("parent "). appendChild (child );}

    This code mainly obtains the child node on the page and adds it to the specified location. You can see that the original child node is moved to the parent.

    Note: If a child is bound to an event, it is still bound to the event when it is moved.

    InsertBefore

    Before insertBefore is used to add a node to a reference node, the usage is as follows:

    parentNode.insertBefore(newNode,refNode);

    ParentNode indicates the parent node after the new node is added.
    NewNode indicates the node to be added.
    RefNode indicates the reference node. The new node will be added to this node.
    Let's look at this example.

    Parent node

    Child Element

    Var parent = document. getElementById ("parent"); var child = document. getElementById ("child"); document. getElementById ("insertNode "). onclick = function () {var newNode = document. createElement ("p"); newNode. textContent = "new node" parent. insertBefore (newNode, child );}

    This Code creates a new node and adds it to the child node.

    Like appendChild, if the inserted node is a node on the page, the node is moved to the specified position and the bound events are retained.

    Pay attention to the second parameter reference node:

    (1) refNode is required. If this parameter is not set, an error is returned.
    (2) If the refNode is undefined or null, insertBefore adds the node to the end of the child element.

    RemoveChild

    As the name implies, removeChild deletes the specified subnode and returns the result. The usage is as follows:

    var deletedChild = parent.removeChild(node);

    DeletedChild points to the reference of the deleted node. It is equal to node and the deleted node is still in memory. You can perform the next operation on it.

    Note: If the deleted node is not its subnode, the program reports an error. We can use the following method to ensure deletion:

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

    Obtain and delete the parent node of the node.

    ReplaceChild

    ReplaceChild is used to replace another node with one node. The usage is as follows:

    parent.replaceNode(newChild,oldChild);

    NewChild is a replacement node. It can be a new node or a node on the page. If it is a node on the page, it will be transferred to a new location.

    OldChild is the replaced node.

    Summary of page modified APIs

    The page modified api mainly includes these four interfaces. Note the following features:

    (1) Whether it is adding or replacing a node, if the newly added or replaced node already exists on the page, the node in the original position will be removed, that is to say, the same node cannot exist in multiple locations on the page.
    (2) will events bound to the node disappear and will be retained.

    Node query API

    Node query APIs are also very commonly used. The following describes the use of each API.

    Document. getElementById

    This interface is simple. An Element is returned Based on the Element id. The returned value is of the Element type. If this Element does not exist, null is returned.

    Note the following points when using this interface:

    (1) The element Id is case sensitive and must be written to the element id.
    (2) If the HTML document contains multiple elements with the same id, the first element is returned.
    (3) only search for elements from the document. If an element is created and the id is specified but not added to the document, the element will not be found.

    document.getElementsByTagName

    This interface gets an element based on the element Tag Name and returns an instant HTMLCollection type. What is an instant HTMLCollection type? Let's take a look at this example.

    P

    P

    Var pList = document. getElementsByTagName ("p"); document. getElementById ("btnAddDiv "). onclick = function () {var p = document. createElement ("p"); p. textContent = "p" + (pList. length +); document. body. appendChild (p);} document. getElementById ("btnShowCount "). onclick = function () {alert (pList. length );}

    There are two buttons in this Code. One button is to display the number of HTMLCollection elements, and the other button can add a p tag to the document. The HTMLCollcetion element mentioned above indicates that the Set changes at any time, that is, there are several p in the document, which will change at any time. When we add a p, when you access HTMLCollection, the added p is contained.

    Note the following when using document. getElementsByTagName:

    (1) If you want to perform cyclic operations on the HTMLCollection set, it is best to cache its length, because the length will be calculated for each loop. Temporarily caching can improve efficiency.
    (2) If no tag exists, the interface returns an empty HTMLCollection instead of null.
    (3) "*" indicates all tags

    document.getElementsByName

    GetElementsByName is mainly used to obtain the element through the specified name attribute. It returns an instant NodeList object.

    Pay attention to the following points when using this interface:

    (1) The returned object is an instant NodeList, which changes at any time.
    (2) In HTML elements, not all elements have the name attribute. For example, p does not have the name attribute, but if the name attribute of p is set forcibly, it can also be found
    (3) In IE, if the id is set to a value and the parameter value of getElementsByName is the same as the id value, this element will be found, therefore, it is better to set the same value to id and name.

    document.getElementsByClassName

    This API returns an instant HTMLCollection Based on the element class. Its usage is as follows:

    var elements = document.getElementsByClassName(names);

    Note the following points for this interface:

    (1) The returned result is an instant HTMLCollection, which will be changed at any time according to the document structure.
    (2) browsers below IE9 are not supported
    (3) If you want to obtain more than two classname types, you can input multiple classname types, each of which is separated by spaces. For example

    Var elements = document. getElementsByClassName ("test1 test2"); document. querySelector and document. querySelectorAll

    These two APIs are very similar. You can use the css selector to find elements. Note that the selector must comply with the CSS selector rules.
    First, we will introduce document. querySelector.

    Document. querySelector returns the first matched element. If no matched element exists, null is returned.

    Note that because the first matched element is returned, this api uses the deep-first search to obtain the element.Let's look at this example:

     

    Level 3 span

    Second p at the same level

    Document. getElementById ("btnGet "). addEventListener ("click", function () {var element = document. querySelector (". test "); alert (element. textContent );})

    This example is very simple, that is, two classes contain "test" elements, one before the document tree, but it is at the third level, and the other is behind the document tree, however, at the first level, when querySelector is used to obtain an element, it performs a deep-first search to obtain the third-level element in front of the document tree.

    The difference between document. querySelectorAll is that it returns all matched elements and can match multiple selectors. Let's take a look at the following example.

     

    Class is test

    Id is test

    Document. getElementById ("btnShow "). addEventListener ("click", function () {var elements = document. querySelectorAll ("# test ,. test "); for (var I =, length = elements. length; I

    This Code uses querySelectorAll to select two elements by using the id selector and class selector, and outputs the content in sequence. Pay attention to the following two points:

    (1) querySelectorAll is also based on deep priority search. The order of the searched elements is irrelevant to the order of the selector.
    (2) The returned result is a non-real-time NodeList. That is to say, the result will not change as the document tree changes.

    Compatibility problem: querySelector and querySelectorAll are not supported in ie8.

    Node relational api

    In the html document, the relationship between each node can be viewed as a family tree, including a parent-child relationship and a sibling relationship. Next we will look at each relationship in sequence.

    Parent relational api

    ParentNode: each node has a parentNode attribute, which indicates the parent node of the element. The parent node of an 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.

    Sibling relational api

    Previussibling: the previous node of the node. If the node is the first node, It is null. Note that the possible nodes are text nodes or comment nodes, which do not conform to expectations. You need to handle them.
    Previuselementsibling: returns the previous Element Node. The previous Element must be an Element. Note that the browser below IE9 does not support this Element.

    NextSibling: The next node of a node. If the node is the last node, It is null. Note that it is possible that the obtained node is a text node, which is inconsistent with the expectation and must be processed.
    NextElementSibling: returns the last Element node, which must be an Element. Note that the browser below IE9 does not support this node.

    Sub-relational api

    ChildNodes: returns an immediate NodeList, indicating the list of child nodes of the element. The child node may contain text nodes, comment nodes, and so on.
    Children: A Real-Time HTMLCollection with all sub-nodes being Element, which is not supported by browsers earlier than IE9.
    FirstNode: The first subnode
    LastNode: The last subnode.
    HasChildNodes method: used to determine whether a subnode is included.

    Element attribute api

    SetAttribute
    SetAttribute: modifies the attributes of an element based on the name and value. The usage is as follows.

    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.
    If the element itself contains the specified property name, you can assign values to the world access property. For example, the following two codes are equivalent:

     element.setAttribute("id","test"); element.id = "test";

    GetAttribute

    GetAttribute returns the feature value corresponding to the specified feature name. If no feature value exists, null or a null string is returned. The usage is as follows:

    var value = element.getAttribute("id");

    Element style api

    window.getComputedStyle

    Window. getComputedStyle is used to obtain the style after an element is applied. Assume that the height of an element is not set but is extended by its content. getComputedStyle is used to obtain the height of an element. The usage is as follows:

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

    Element is the element to be obtained, and the pseudo element is specified for matching.

    The returned style is a CSSStyleDeclaration object.

    Style allows you to access the style after element calculation.

    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 left, top, right, and bottom. It is the distance from the visible window. When the rolling position changes, their values change. In addition to browsers earlier than IE9, the browser also contains data such as the height and width of the element. For details, see the link.

    Summary

    This article mainly summarizes the APIs used to operate DOM in native js, mainly to review the basic knowledge. When jQuery and other class libraries are used for development at ordinary times, the basic knowledge may be gradually forgotten, but these basic knowledge is the foundation of our foothold. Only by mastering the native js, in order to truly develop js.

    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.