JavaScript Dom Common API summary

Source: Internet
Author: User
Tags return tag tag name

JavaScript Dom Common API summary Wolf Wolf's blue fat URL: http://www.cnblogs.com/lrzw32/p/5008913.html text organizes some of the common APIs used by JavaScript to manipulate the DOM, According to its role to organize to create, modify, query and other types of API, mainly used to review the basic knowledge, deepen the understanding of the native JS. Basic concepts before we explain the API for manipulating the DOM, let's review some basic concepts that are key to mastering the API and must be understood. The node type 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:1node.attribute_node:2node.text_node : 3node.cdata_section_node:4node.entity_reference_node:5node.entity_node:6node.processing_instruction_node : 7node.comment_node:8node.document_node:9node.document_type_node:10node.document_fragment_node:11node.notation _node:12 Suppose we want to determine if a node is an element, so we can judge if (Somenode.nodetype = = 1) {Console.log ("node is a element");} 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 these types: element type elements provide access to tag names, child nodes, and attributes, and tags such as div,span,a, which are commonly used in HTML elements such as a. element has the following characteristics: (1) NodeType is 1 (2) nodename is the element tag name, TagName is also the return tag name (3) nodevalue to null (4) PARentnode may be a document or element (5) child node may be element,text,comment,processing_instruction, The cdatasection or Entityreferencetext 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 features: (1) NodeType for 3 (2) NodeName for #text (3) NodeValue for text content (4) parentnode is an element (5) No child node attr type attr type represents the attributes of the element, Corresponds to the node in the attributes attribute of the element, It has the following characteristics: (1) The NodeType value is 2 (2) nodename is the name of the attribute (3) NodeValue is the value of the attribute (4) parentnode for Nullcomment type comment represents the comment in the HTML document, It has the following characteristics: (1) NodeType is 8 (2) nodename for # Comment (3) NodeValue for annotated content (4) ParentNode may be document or element (5) No child nodes documentdocument represent documents in the browser, The Document 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) child node may be a DocumentType or elementdocumentfragment type documentfragment is the only one in all nodes that does not have a The type that should be marked, 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 for one (2) nodename for # Document-fragment (3) NodeValue is null (4) parentnode is null we simply introduced several common node types, keeping in mind that the nodes in HTML do not just include 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-created APSI am here to classify the commonly used DOM operations API, first of all to introduce the creation-type API. This type of API, in short, is used to create nodes. Createelementcreateelement 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 to note: Elements created through createelement are not part of an HTML document, they are simply created, is not added to an HTML document and is added to the HTML document tree by calling methods such as AppendChild or InsertBefore. Createtextnodecreatetextnode is used to create a text node using the following: var Textnode = document.createTextNode ("one Textnode"); createTextNode receives a parameter, which is the text in the text node, and, like CreateElement, the created text node is just a separate node. It is also necessary to add appendchild to the HTML document tree Clonenodeclonenode 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);//Incoming trueparent2.id = "Parent2"; This code copies a copy of the parent element through CloneNode, Where the CloneNode parameter is true, the child node of the parent is also copied, and if passed false, it means that only the parent node is replicated. I am the text of the parent element
I'm a child element .Copyvar parent = document.getElementById ("parent");d Ocument.getelementbyid ("Btncopy"). onclick = function () {var parent2 = Parent.clonenode (TRUE); Parent2.id = "Parent2"; Document.body.appendChild (Parent2);} 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) As with createelement, the node created by CloneNode is simply a node that is free of HTML documents, and to invoke 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, it is necessary to modify its ID (3) After the node is copied to the best incoming bool parameter, and if the parameter is not passed in, different browsers may treat their default values differently. In addition, we have a point to note: If the replicated node is bound to an event, Will the copy also bind to the event? Here to discuss the situation: (1) If the binding event is done through AddEventListener or for example onclick, the replica node will not bind the event (2) if it is inline-bound, such as this, the replica node will also trigger the event. The Createdocumentfragmentcreatedocumentfragment 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
    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) {var li = document.createelement ("li"); li.textcontent = i; Fragment.appendchild (li);} list.appendchild (fragment);} The optimized code is mainly to create a fragment, each of the generated Li node first added to fragment, and finally added to the list, you can see the sample creation API summary creation API mainly includes createelement, Createtextnode,clonenode and Createdocumentfragment Four methods, note the following points: (1) The node they create is just an isolated node, To add to the document via AppendChild (2) CloneNode Note If the replicated node contains child nodes and event bindings (3) using Createdocumentfragment to resolve the addition of a large number of nodesPerformance Issues 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. Appendchildappendchild 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 method of invocation is as follows: Parent.appendchild (child); 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. The node to be added


    The location to movedocument.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. Here's another point to note: If a child is bound to an event and is moved, it is still bound to the event. Insertbeforeinsertbefore used to add a node to a reference node, use the following: Parentnode.insertbefore (Newnode,refnode); ParentNode indicates that the new node is added after the parent node NewNode represents the node to be added Refnode represents the reference node, and the new node is added to the node before the parent section PIP element var parent = document.getElementById ("parent"), var child = document.getElementById ("child");d Ocument.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 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, Then InsertBefore adds the node to the end of the child element Removechildremovechild as the name implies, deleting the specified child node and returning it, using the following: var Deletedchild = Parent.removechild ( node);d Eletedchild points to the deleted node's reference, which equals node, the deleted nodes still exist in memory and can be taken to the next step. Note: If the deleted node is not its child node, the program will error. We can make sure that we can delete: if (node.parentnode) {node.parentNode.removeChild (node) in the following way;} Gets the parent node of the node itself through the node, and then deletes itself. Replacechildreplacechild is used to replace another node with one node, using the following Parent.replacenode (Newchild,oldchild), NewChild is the replacement node, which can be a new node, It can also be a node on the page, if it is a node on the page, it will be transferred to the new location Oldchild is the replacement node page Modified API Summary page modified 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 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) the event that the node itself binds to will not disappear and will remain. NodeQuery API node Query API is also a very common API, below we explain each of the use of the API. 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) The HTML document may have more than one ID of the same element, then return the first element (3) only search elements from the document, if an element is created and an ID is specified, But it was not added to the document, This element is not to be found document.getElementsByTagName this interface gets the element based on the element tag name, returns an immediate htmlcollection type, what is the immediate htmlcollection type? Let's take a look at this example Div1div2 var divlist = document.getelementsbytagname ("div");d Ocument.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. Use document.getElementsByTagName This method has a few points to note: (1) If you want to loop the Htmlcollection collection, it is best to cache its length, because each cycle will calculate the length, the temporary cache can improve efficiency (2) If there is no specified Label, the interface returns not NULL, but an empty htmlcollection (3) "*" Represents all labels Document.getelementsbynamegetelementsbyname the element is obtained primarily 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, it is changed at any time (2) in the HTML element, not all elements have the name attribute, such as Div is not the name attribute, but if the name property of the Div is forced to set, It can also 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's best not to set the same value to the ID and Namedocument.getelementsbyclassname this API is to return an immediate htmlcollection based on the class of the element, using the followingvar elements = document.getelementsbyclassname (names); This interface has the following points to note: (1) The return result is an immediate htmlcollection, Will change depending on 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, such as var elements = Document.getelementsbyclassname ("Test1 test2"); Document.queryselector and Document.queryselectorall are similar to the two APIs, looking for elements through a CSS selector, noting 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.the third level of spanSecond DIV of siblingdocument.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. The difference in Document.queryselectorall is that it returns all matching elements, and can match multiple selectors class for test ID testdocument.getElementById ("Btnshow"). AddEventListener ("click", Function () {var elements = Document.queryselectorall (" #test,. Test "); for (var i = 0,length = Elements.length;i JavaScript 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.