Js miscellaneous-DOM

Source: Internet
Author: User
Preface dependencies on jQuery. As a result, the native method of js is forgotten. If it is to encapsulate its own library, it is necessary to use many native methods of js. Starting with Jquery's powerful dom processing, let's look back at javascript's ancient and strong DOM methods. Start with level 0 DOM. 1 node type... SyntaxHighlighter. all (Preface dependencies on jQuery. As a result, the native method of js is forgotten. If it is to encapsulate its own library, it is necessary to use many native methods of js. Starting with Jquery's powerful dom processing, let's look back at javascript's ancient and strong DOM methods. Start with level 0 DOM. 1 node type: nodeType name1 element_node2 comment text_node4 Comment comment entity_node7 comment comment_node9 document_node10 document_type_node11 comment notation_node1.1 dom basic operation. js has the right to add, delete, modify, and query the dom tree. createElement () // create a fatherNode. appendChild () // Add fatherNode. replaceChild ('newnode', 'oldnode') // change fatherNode. childNodes [0-N] // query fatherNode. removeChild (node) // delete a childNodes containing text nodes and comment nodes. Pay attention to it when using it. When adding or replacing nodes, no additional text nodes are added. All operation permissions are generally on the parent node. Here, there is a cloneNode () method, which has a parameter. true indicates deep replication. You can copy sub-elements of this element. false indicates light replication and can only copy itself. In versions earlier than IE9, there is a problem: in deep replication, they do not create nodes for blank characters. 2 element Type 2.1 Document Element Node Type document nodeType 9 nodename' # document 'nodevalue nullparentNode nullownerDocument null document indicates the Document. In the browser, when the Document object is HTMLDocument (inherited from the document Type) the entire page. But an attribute of the window object when the document object is used. Documenthas two internal parameters: 1. Doc umentElement: directly obtain htmlelement. equal to childnodes1_0133, firstchild2.doc type: Get document type node where the first attribute is supported by all browsers, and the second attribute: IEn-8 parses it into comment nodes. Therefore, the value is nullIE9 + FF: It is parsed into the first subnode of the document. chrome safari opera: It can be parsed, but not as a subnode of the document. The document Object also provides some attributes not included in the standard Document object, which provide some information about the webpage. Console. log (document. title); // webpage title console. log (document. URL); // path to console. log (document. domain); // domain name console. log (document. referrer); // The url linked to the previous page can only be set for the domain name. websites with the same domain name can access each other using javascript. The following is a convenient method. Document. anchors // All a labels document. applet // all the applet labels document. forms // All form elements document. images // contains all img elements document. links // The Document type of all the tags with the href feature provides two methods: getElementById and getElementsByTagName in IE8 and earlier versions do not distinguish the case sensitivity of IDs. In addition, IE7 and earlier versions also add an interesting "geek" for this method: name features form elements (input, textarea, button, select) that match a given ID) this method also returns the result. If the name attribute of a form element is equal to the specified ID, and the element is located before the element of the given ID in the document, then IE will return the form element. However, to avoid this problem in IE, it is best not to let the name attribute of the form field be the same as the ID of other elements. Another method is getElementsByTagName. This method accepts a parameter to obtain the tag name of an element, and returns a NodeList containing zero or multiple elements. In the HTML document, this method returns an HTMLCollection object as a "dynamic" set, which is very similar to nodeList. Here, the HTMLCollection object also saves a method namedItem (). This method can be used to obtain items in the set through the name feature of the element. In addition, HTMLCollection also supports access by name, this makes it easier for us to get the actually desired elements, and you can also access the named items using square brackets syntax. In general, for HTMLCollection, We can input a numerical value or string-form index value to square brackets. In the background, the value index will call item (), and the string index will call namedItem. Another method is getElementByName (), this method returns all elements of the given name feature. This method is usually used on radio. The following four methods are also returned: write (), writeln (), open (), close (). The write () and writeln () methods both accept a string parameter, that is, the text to be written to the output stream, write () will be written as is, while writeln () A linefeed (\ n) will be added at the end of the string. When the page is loaded, you can use these two methods to dynamically add content to the page. The open and close methods are used to open and close the output streams of the webpage, respectively. If the write () or writeln () method is used during page loading. 2.2 The label name nodeValue nullparentNode Element or Document 2.2.1 of Element nodeName is represented by the HTMLCollection type. Each element node has attributes. The standard methods include getAttribute (), setAttribute (), and removeAttribute (). The Element type is the only DOM node type using the attributes attribute. The attributes attribute contains a NameNodeMap. Similar to nodelist, a dynamic set has two special features. Although they have corresponding attribute names, however, the attribute value is different from the value returned by getAttribute. The first type of feature is style, which is used to specify styles for elements through css. When you access the object through getAttribute, the returned style property value contains css text, and an object is returned when you access the object through properties. The style attribute is used to access element styles programmatically. The second distinctive feature is the event handler such as onclick. IE6 and earlier versions do not support removeAttribute 2.2.2 the Element type of the attributes attribute is the only DOM node type using the attributes attribute. The attributes attribute contains a NamedNodeMap. Similar to NodeList, it is also a dynamic set. Each feature of an element is represented by an Attr node, and each node is saved in the NamedNodeMap object. The API is as follows: getNamedItem (name): return the node removeNamedItem (name) with the nodeName attribute equal to name: remove the node setNamedItem (node) with the nodeName attribute equal to name from the list ): add a node to the list and index item (pos) with the nodeName attribute of the node: return the node at the position of the digital pos. Generally, because the attributes method described earlier is not convenient enough, more developers will use getAttribute, setAttribute, and removeAttribute to describe attributes. For the characteristics of attributes objects, different browsers return different order. The order in which these features appear in XML or HTML code is not necessarily the same as the order in which they appear in attributes objects. IE7 and earlier versions will return all possible features in the HTML element, including unspecified features. In other words, it is common to return more than 100 features. For problems in IE7 and earlier versions, let it only return the specified features. Each feature node has an attribute named specified. If the value of this attribute is true, it means either specifying the corresponding feature in HTML or setting this feature through setAttribute, in IE, this attribute for all features that have not been set is false2.2.3 creating element document. createElement ('xx'); the receiving parameters are case-insensitive. in XML, they are case-sensitive. Setting features on new elements only gives them corresponding information. Since the new elements have not been added to the document tree, setting these features does not affect Browser display. To add new elements to the document tree, you can use the appendChild, insertBefore, or replaceChild methods. Once an element is added to the document tree, the browser immediately presents the element. Any modifications made to this element are reflected in the browser in real time. Note: in IE, you can use createElement in another way, as shown in the following code: var div = document. createElement ("") is similar to jQuery. This method helps avoid some problems of dynamically creating elements in IE7 and earlier versions: The name feature of dynamically creating iframe elements cannot be set through reset () of the form () method resetting dynamically created input the type feature value is reset the button element cannot reset a batch of dynamically created single-choice buttons with the same name in the form, there is no relationship with each other, and the single-choice effect cannot be achieved. All of the above mentioned problems can be solved by specifying the complete HTML Tag in createElement. 2.2.4 the child node element of an element can have any number of child nodes and child nodes, because the element can be a child node of other elements. The childNodes attribute of the element contains all its subnodes. These subnodes may be elements, text nodes, comments, or processing commands. There are significant differences in viewing these nodes in different browsers. For example:
  • 1
  • 2
  • 3
If the code is parsed by IE, ul has three subnodes. If it is another browser, it will be 7 subnodes, that is, three li nodes and four Text nodes. 2.3 Text element nodeType 3 nodeName # Text content contained in textnodeValue parentNode element can access the Text contained in the Text node through the nodeValue and data attributes. The two attributes contain the same values. The API is as follows: appendData (text): Add text to the end of the node deleteData (offset, count): delete count characters from the position specified by offset. InsertData (offset, text): Insert text from the position specified by offset. ReplaceDate (offset, count, text): Replace text from the specified position of offset to offset + count with text. SplitText (offset): the text is divided into two text nodes from the position specified by offset. SubstringData (offset, count): extract the string from the specified position of offset to the position of offset + count. The above methods are mainly used to operate text nodes, rather than text nodes. By default, each element that can contain content can have only one text node. And the content must exist. 2.3.1 create a text node document. createTextNode (). This method receives a parameter-that is, the text of the node to be inserted, which is the same as setting the value of an existing text node. If the two text nodes are adjacent compatriot nodes, the text in the two nodes will be connected and displayed without spaces in the middle. 2.3.2 The standardization text node DOM document contains adjacent compatriot text nodes, which can easily lead to confusion, because it cannot tell which text node represents which string. When the normalize () method is called on a parent element that contains two or more text nodes, all text nodes are merged into one node, the nodevlaue of the result node is the value that Concatenates the nodeValue of each text node before the merge. 2.3.3 split Text node the Text type provides a method opposite to normalize (): splitText (), which divides a Text node into two Text nodes: that is, the nodeValue is separated by the specified position. The value 2.4 indicates that the content of the annotation node nodeType 8 nodeName # commentnodeValue is parentNode Document or the ElementComment type and Text type are inherited from the same base class, therefore, it has all the string operation methods except splitText. Similar to the text type, you can also obtain the annotation content through the nodeValue or data attribute. For example, you can access a comment var div = document. getElementById ('mydiv '); var comment = div. firstChild; alert (comment. data); similarly, annotations can also be created using document. createComment () method. Its parameter is to input the annotation text. 2.5 The content parentNode Document or element in the nodeType 4 nodeName # CDATA-sectionnodeValue cdata region does not support subnodes. The CDATA area appears in the XML document. Therefore, most browsers incorrectly parse the CDATA area into Comment or Element. You can use document. createCDataSection () to create a CDATA region in an XML file. 2.6 The DocumentType type nodeType 10 nodeName doctypenodeValue nullparentNode DocumentDocumentType is not common in web browsers. It is only supported by FF, safari, and opera. At the DOM1 level, the DocumentType object cannot be dynamically created, but can only be created by parsing the document code. The page view that supports this function stores the documenttypeobject in document.doc type. DOM1 describes three attributes of the DocumentType object: name, entities, and notations. Specifically, name indicates the document type name; entities is the NamedNodeMap object of the entity described by the document type; notations is the NamedNodeMap object of the symbol described by the document type. Generally, documents in the browser use HTML or XHTML document types, so entities and notations are empty lists (the items in the list come from the intra-row Document Type Declaration ). However, in any case, only the name attribute is useful. The document type name is saved in this attribute. 2.7 The document segment nodeType 11 nodeName # document-fragmentnodeValue nullparentNode null is of all node types, and only DocumentFragment does not have the corresponding tag in the document. DOM specifies that a document segment is a lightweight document that can contain and control nodes, but does not occupy additional resources as full documents do. Although you cannot add the part that smells it to the document directly, you can use it as a repository. You can save the nodes that may be added to the document in the future. Create a document clip. You can use the following method: the document segment of document. createDocumentFragment () inherits all methods of Node and is usually used to perform DOM operations on documents. If a node in the document is added to the document segment, the node is removed from the document tree. 2.8 The value of the namenodeValue attribute of the nodeType 2 nodeName feature parentNode null is not considered part of the DOM document tree although they are also nodes. The Attr object has three attributes: name, value, and specified. specified is a Boolean value, which is used to differentiate features specified in the Code. 3. DOM part operation technology 3.1 dynamic script objective: script elements can be inserted like javascript code on a page. The src feature contains external files. This element is used to include code 3.2 dynamic styles. The so-called dynamic styles mean that styles do not exist during page loading. style; dynamic styles are dynamically added to the page after the page is loaded. The process of loading external style files is asynchronous. That is to say, there is no fixed order between the process of loading styles and executing javascript code. Generally, it is not important to know that the style has been loaded. 3.3 operation table DOM1 provides API caption for some operation tables to save the pointer to the caption element tBodies is a tBody element HTMLCollectiontFoot to save the pointer to the tFoot element tHead to save thead Element rows is the HTMLCollectioncreateTHead () of all rows in a table () create thead element, put it into the table, return reference createTFoot () Create tFoot element, put it into the table, return reference createCaption () Create caption element, put it into the table, return reference deleteTHead () delete thead element deleteTFoot () delete TFoot element deleteCaption () delete caption element deleteRow (pos) Delete row insertRow (pos) at the specified position) delete the row tbody-rows at the specified position and save t The HTMLCollectiontbody-deleteRow () of the row in the body element deletes the row tbody-insertRow () at the specified position in the rows set to insert a row, returns the reference to the newly inserted row tr-cells. Saves the HTMLCollectiontr-deleteCell (pos) of the cell in the tr element and deletes the cell tr-insertCell (pos) at the specified position) insert a cell to a specified position in the cells set and return a reference to the new cell. 3.4 about using NodeList to understand NodeList and its relatives NamedNodeMap and HTMLCollection are the key to a complete understanding of DOM, these three sets are all "dynamic". In other words, if the document structure changes, they will be updated. Therefore, they always store the latest and most accurate information. In essence, all NodeList objects are queried in real time when accessing DOM documents.
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.