Common API Summary _javascript techniques based on JavaScript operations DOM

Source: Internet
Author: User
Tags object model tag name

Objective

The DOM (Document Object model), which is an API for HTML and XML documents (the application interface) The DOM depicts a hierarchical node tree that runs a developer to add, remove, and modify portions of a page. DOM was born of the DHTML (dynamic HTML) originated by Netscape and Microsoft, but now it has become a truly cross-platform, language-neutral way of performing and manipulating page tags.

Reading Table of Contents

Basic concepts
Node-creation API
Page Modification API
Node Query-type API
Node-Relational API
Element attribute-Type API
Element-style API

Summarize

Text collation of JavaScript operations dom some of the common API, according to its role in the collation of the creation, modification, query and other types of APIs, 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 of the basic concepts that are key to mastering the API and must be understood.

Node type

The DOM1 level 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. The following versions of IE9 are inaccessible to this type, and all nodes in JS inherit from node types and share the same basic properties and methods.

Node has an attribute NodeType representing 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're going to judge whether a node is an element, we can judge that.

 if (Somenode.nodetype = =) {
   Console.log ("Node is a element");
 }

Of these node types, our most common use is the element,text,attribute,comment,document,document_fragment of these types.
Let's briefly introduce these types:

Element type

Elements provide access to element tag names, child nodes, and attributes, and we often use HTML elements such as Div,span,a tags as one of the element. element has the following characteristics:

(1) NodeType is 1
(2) NodeName is the element label name, TagName is also the return sign signature
(3) NodeValue is null
(4) ParentNode may be document or element
(5) The child node 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 as text content
(4) ParentNode is an element
(5) No child nodes

attr type

The attr type represents the attributes of an element, which corresponds to the node in the element's Attributes property, which has the following attributes:

(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 that has the following characteristics:

(1) NodeType is 8
(2) NodeName for #comment
(3) NodeValue as the content of the annotation
(4) ParentNode may be document or element
(5) No child nodes

Document

Document represents the documentation, in the browser, that the document object is an instance of HTMLDocument, representing the entire page, which is also a property of the Window object. The document has the following characteristics:

(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 might be used as a temporary repository to hold nodes that might be added to the document. DocumentFragment has the following characteristics:

(1) NodeType is 11
(2) NodeName for #document-fragment
(3) NodeValue is null
(4) ParentNode is null

We briefly introduce several common node types, and remember that the nodes in HTML do not just include element nodes, it also includes text nodes, annotation nodes, and so on. Here we simply explain a few common nodes, want to further study students can look up the relevant information.

Node-creation API

Here, I classify the common DOM operations APIs, first of all to introduce the creation-type 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 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 to note that elements created by createelement are not part of an HTML document, but are created and not added to an HTML document. To invoke methods such as AppendChild or insertbefore, add it to the HTML document tree.

createTextNode

createTextNode is used to create a text node, as follows:

var textnode = document.createTextNode ("a Textnode");

createTextNode receives a parameter, which is the text in a text node, and like CreateElement, the created text node is just a separate node, and it also needs 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 that indicates whether to copy the child elements, using the following:

 var parent = document.getElementById ("parentelement"); 
 var parent = Parent.clonenode (true);//Pass in true
 parent.id = "parent";

This code copies a copy of the parent element through CloneNode, where the CloneNode argument is true, and the child node of parent is replicated, and if False is passed, only the parent node is replicated.

Let's take a look at this example

<div id= "Parent" >
   I am the text of the parent element
   <br/>
   <span>
     I am the child element
   </span>
 </div >
 <button id= "btncopy" > Replication </button>
 
 var parent = document.getElementById ("parent");
 document.getElementById ("Btncopy"). onclick = function () {
   var parent = Parent.clonenode (true);
   Parent.id = "parent";
   Document.body.appendChild (parent);
 }

This code is simple, mainly binding the button event, which copies a parent, modifies its ID, and then adds it to the document.

Here are a few points to note:

(1) As with createelement, CloneNode creates nodes that are free of nodes outside the HTML document, to invoke the AppendChild method to add to the document tree
(2) If the copied element has an ID, the copy also contains the ID, and because the ID is unique, the ID must be modified after the node is replicated
(3) The invocation of the received bool parameter is best passed in, and if not passed in, different browsers may have different processing of their default values

In addition, we have a point to note:

If the replicated node binds the event, does the copy also bind to the event? Here's how it's going to be discussed:

(1) The replica node does not bind the event if it is bound by addeventlistener or, for example, onclick
(2) If it is inline binding such as

 <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 the front we said that DocumentFragment represents a lightweight document,

Its role is primarily to store temporary nodes that are ready to be added to the document.
The Createdocumentfragment method is used primarily when adding a large number of nodes to a document. Suppose you want to loop through a set of data and then create multiple nodes to add to your document, such as an example

<ul id= "List" ></ul>
 <input type= "button" value= "Add multiple Items" id= "
 btnadd"/> 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 a button to an event that creates 100 Li nodes and then adds them to the HTML document in turn. This has one drawback: each time a new element is created and then added to the document tree, the process can cause the browser to return. The so-called backflow simply means that the size and position of the element will be recalculated, and if too many elements are added, it can cause performance problems. This time, is to use the createdocumentfragment.

DocumentFragment is not part of the document tree, it is stored in memory, so it does not cause reflux 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 =; I < i++) {
    var li = document.createelement ("li");
     Li.textcontent = i;
     Fragment.appendchild (li);
   }
   List.appendchild (fragment);
 }

The optimized code is mainly to create a fragment, each generation of Li node first added to the fragment, the last one-time add to the list, you can see the example

Create API Summary

The creation API consists mainly of Createelement,createtextnode,clonenode and createdocumentfragment four methods, which need to be noted below:

(1) The node they create is just an orphaned node that is added to the document through AppendChild
(2) CloneNode should note if the replicated node contains child nodes and event binding issues
(3) using Createdocumentfragment to solve performance problems when adding a large number of nodes

Page Modification API

Earlier we mentioned the Create-type APIs, which simply create the nodes and do not actually modify the page content, but instead invoke appendchild to add it to the document tree. I am here to classify this type of content as being modified to a page.

The main API for modifying page content includes: Appendchild,insertbefore,removechild,replacechild.

AppendChild

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

Parent.appendchild (child);

The child node will be the last node of the parent node.

AppendChild This method is very simple, but there's one more thing to note: If the node being added is a node that exists on a page, then the node will be added to the specified location when it is executed, and that node will be removed in its original location, which means there will not be two nodes on the page at the same time. The equivalent of moving this node to another place. Let's look at the example

<div id= "Child" >
   node to be added
 </div>
 <br/>
 <br/>
 <br/>
 <div Id= "parent" >
   position to move
 </div>    
 <input id= "btnmove" type= "button" value= "Mobile node"/>
 document.getElementById ("Btnmove"). onclick = function () {
   var child = document.getElementById (' child ');
   document.getElementById ("parent"). AppendChild (child);
 }

This code is primarily to get the child node on the page and then add it to the specified location to see that the original child node was moved to parent.

Here's another point to note: If the child binds the event, it still binds the event when it is moved.

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 add
Refnode represents the reference node, and the new node is added before this node
Let's look at this example

<div id= "Parent" >
   parent node
   <div id= "Children" >        
     child elements
   </div>
 </div>
 < Input type= "button" id= "Insertnode" value= "Insert Node"/>
 var parent = document.getElementById ("parent");
 var child = document.getElementById ("child");
 document.getElementById ("Insertnode"). onclick = function () {
   var newNode = document.createelement ("div");
   newnode.textcontent = "New Node"
   Parent.insertbefore (Newnode,child);
 }

This code creates a new node and then adds it before 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 its bound events are preserved.

There are several points to note about the second parameter reference node:

(1) Refnode is required, if not transmitted this parameter will be the error
(2) If the refnode is undefined or null, InsertBefore adds the node to the end of the child element

RemoveChild

RemoveChild, as the name suggests, is to delete the specified child nodes and return them, using the following:

var deletedchild = parent.removechild (node);

Deletedchild points to a reference to the deleted node, which is equal to node, and the deleted node still exists in memory and can be taken next.

Note: If the deleted node is not its child node, the program will make an error. We can make sure that we can delete the following ways:

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

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

ReplaceChild

ReplaceChild is used to replace another node with one node, as follows

Parent.replacenode (Newchild,oldchild);

Newchild is a replacement node, either a new node or a node on the page, and if it is a node on the page, it will be moved to a new location

Oldchild is the node being replaced

Page Modification API Summary

The page modifies the API mainly is these four interfaces, must pay attention to several characteristics:

(1) Whether the new or replacement node, if the new or replacement node is originally on the page, then its original location of the node will be removed, that is, the same node can not exist in multiple locations on the page
(2) The event that the node itself binds will not disappear and will remain.

Node Query-type API

Node query-type API is also a very common API, below we explain the use of each API.

document.getElementById

This interface is simple, returns an element based on the element ID, the return value is the element type, or null if no element exists.

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 the ID is specified but not added to the document, the element is not found

document.getElementsByTagName

This interface gets the element based on the element tag name, returns an instant htmlcollection type, what is the instant htmlcollection type? Let's take a look at this example

<div>div</div>
 <div>div</div>
 <input type= "button" value= "Display Quantity" id= " Btnshowcount "/>
 <input type=" button "value=" New div "id=" btnadddiv "/>  
 var divlist = document.getElementsByTagName ("div");
 document.getElementById ("Btnadddiv"). onclick = function () {
   var div = document.createelement ("div");
   div.textcontent = "div" + (divlist.length+);
   Document.body.appendChild (div);
 }
 document.getElementById ("Btnshowcount"). onclick = function () {
     alert (divlist.length);
 }

There are two buttons in this code, one button is to display the number of htmlcollection elements, and another button can add a div tag to the document. The previous mention of the htmlcollcetion element is an immediate indication that the set is always changing, that is, there are several div in the document, it will change at any time, when we add a div, then visit the htmlcollection, will include this new Div.

There are a few things to note about using the document.getElementsByTagName method:

(1) If you want to cycle the Htmlcollection collection, it is best to cache its length, because each loop will calculate the length, 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

Document.getelementsbyname

Getelementsbyname primarily obtains an element by specifying the Name property, which returns an Instant NodeList object.

The main points to use this interface are:

(1) The return object is an instant nodelist, it is always changeable
(2) In HTML elements, not all elements have a name attribute, such as a div without the name attribute, but if you force the div's Name property, 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 the element will be found, so it is better not to set the same value to ID and name

Document.getelementsbyclassname

This API returns an instant htmlcollection based on the element's class, as follows

var elements = document.getelementsbyclassname (names);

This interface has the following points to note:

(1) The return result is an instant htmlcollection, which can be changed 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");
Document.queryselector and Document.queryselectorall

These two APIs are similar, looking for elements through CSS selectors, noting that selectors conform to the rules of CSS selectors.
First of all, to introduce Document.queryselector.

Document.queryselector returns the first matching element, or null if there is no matching element.

Note that because the first matching element is returned, the API uses a depth-first search to get the element. Let's look at this example:

 <div>
   <div>
     <span class= "Test" > Span</span>  
   </div> </div of the third level
 >
 <div class= "Test" >      
   sibling's second div
 </div>
 <input type= "button" id= "Btnget" value= "Get test Element"/>
 document.getElementById ("Btnget"). AddEventListener ("click", Function () {
   var element = Document.queryselector (". Test");
   alert (element.textcontent);
 })

The simple example is that two classes contain "test" elements, one in front of the document tree, but at the third level, the other behind the document tree, but at the first level, when the element is fetched through queryselector, it is searched by depth first, Get the third level element in front of the document tree.

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

 <div class= "Test" >
   class for Test
 </div>
 <div id= "Test" >
   ID is Test
 </div>
 <input id= "btnshow" type= "button" value= "Display content"/>
 document.getElementById ("Btnshow"). AddEventListener ("click", Function () {
   var elements = Document.queryselectorall ("#test,. Test");  
   for (var i =, 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 then prints its contents sequentially. Pay attention to two points:

(1) Queryselectorall is also through depth-first search, the search element order and selector order is irrelevant
(2) A nodelist is returned, which means that the result will 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 an HTML document can be seen as a genealogy relationship, including parent-child relationships, sibling relationships, and so on, and then we'll look at each of these relationships in turn.

Parent-Relational API

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

Brother-Relational API

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

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

Sub-relational API

ChildNodes: Returns an instant 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, the child nodes are ELEMENT,IE9 the following browsers do not support.
Firstnode: First child node
Lastnode: Last child node
HasChildNodes method: Can be used to determine whether to include child nodes.

Element attribute-Type API

SetAttribute
SetAttribute: Modifies the attributes of an element based on its name and value, as follows.

Element.setattribute (name, value);

Where name is the attribute name, 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 name as a property, then the world can access the property for assignment, for example, the following two code is equivalent:

 Element.setattribute ("id", "test");
 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. Usage is as follows:

var value = Element.getattribute ("id");

Element-style API

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 and that it is stretched by its content, at which point the height of the getComputedStyle will be used, as follows:

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

element is the elements to get, pseudoelt specifies a pseudo element to match.

The style returned is a Cssstyledeclaration object.

Style can be accessed after the element is calculated

Getboundingclientrect

Getboundingclientrect is used to return the size of the element and its position relative to the browser's visual window, as follows:

var clientrect = Element.getboundingclientrect ();

Clientrect is a Domrect object that contains Left,top,right,bottom, which is relative to the visual window, and its value changes when the scrolling position changes. In addition to IE9 the following browsers, but also contains the elements of the height and width of data, you can view the link

Summarize

This paper mainly summarizes the common operating Dom API interface in native JS, mainly to review the basic knowledge. Peacetime development with a lot of jquery and other classes of library, the basic knowledge may gradually forgotten, but these basic knowledge is our foothold in the fundamental, only master the original JS, can really do JS development.

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.