(Sixth day) DOM

Source: Internet
Author: User

Concept

The Document Object Model (DOM) is the underlying API for representing and manipulating the content of HTML and XML documents.

Select a document Element (1) Select an element by ID
var id = document.getElementById ("section1");

<input type= "text" id= "Section1" value= "" >

Note: In browsers that are below the IE8 version, getElementById () is not case-sensitive for the ID of the matching element, and also returns the element that matches the name attribute.

(2) Selecting elements by name

The Name property of HTML originally intended to assign a name to the form element, using the value of the property when the form data was submitted to the server. Like the id attribute, name assigns the name to the element, but the value that differs from the Id,name attribute is not unique: multiple elements may have the same name, in the form, the Radio and check box buttons are usually the case. Also, unlike IDs, the Name property is valid only in a few HTML elements, including forms, form elements, <iframe>, and elements.

Select an HTML element based on the value of the Name property, and you can use the Getelementsbyname () method of the Document object.

var arr = document.getelementsbyname ("fav_color");  // by name, returns a HtmlElement collection <input type="text" name="fav_ Color" />

Note: Getelementsbyname () is defined in the HTMLDocument class, not in the document class, so it is available only for HTML documents and is unavailable in XML documents. It returns a NodeList object, which behaves like a read-only group that contains several element objects. by practice, the Getelementsbyname () also returns an element that matches the specified value in IE9 and IE9, as well as the id attribute. For compatibility, be careful not to use the same string for both name and ID.

(3) Get elements by tag name

The Getelementbytagname () method of the Document object can be used to select all HTML or XML elements of the specified type (labeled Signature). For example, get a read-only class array object that contains all the <span> elements in the document.

var spans = document.getElementsByTagName ("span");

<span></span>
(4) Selecting elements from CSS Selectors
#warning  /* through id*/.  warning/* through class*/input       /*  All input elements */<input type='text "class=" warning "  id=" Warning "value=" "> 
(5) document.all[]

Before Dom normalization, IE 4 introduced the document.all[] collection to represent all elements in the document (except the text node). Document.all[] methods have been superseded by standard methods (such as getElementById () and getElementsByTagName ()) and are now obsolete and should not be reused.

The node tree of the document

The document object, its element object, and the text object that represents the literal in the documentation are all node objects. Node defines the following important attributes:

(1) ParentNode The parent node of the node, or it should be null for a similar document object because it does not have a parent node. 【Gets the parent node of the current element】

(2) ChildNodes A read-only class Array object (NodeList object), which is a real-time representation of the node's child nodes "returns all child nodes of the specified node】

(3) FirstChild, lastchild the first and last of the child nodes of the node, or null if the node has no child nodesGets the first (childnodes[0]) or last node (Childnodes[length-1]) of the current node】

(4) NextSibling The next node of the node: get the next Element "The type of this element can contain empty text nodes】

(5) Previourssibling Gets the previous node of the current node "nextelementsibling can only get element nodes.】

Node (1) NodeType "node type"
  • Element (tag) <span></span> 1 for
  • Attr (attribute) <span Color="red"></span denoted by 2
  • Text <span> This was a simple document</span> denoted by 3
  • Comments (note) <!--This is a comments--> with 8
  • Document alert (window.document.nodeType); denoted by 9
(2) NodeName "node name"

The returned results are uppercase, the nodename of the text is #text, and the nodename of the comment is #comment

(3) NodeValue "node value"

Useful only for text nodes and annotations, not for labels

Create, insert, and delete nodes (1) Create element elements node
var element = document.createelement ("span");
(2) Inserting a node

AppendChild () and InsertBefore () methods

varList = document.getElementById ("List");varLi = document.createelement ("Li"); Liappendchild(LI); /*Add the created element Li to the parent element list*/list. InsertBefore (Li, list.childnodes[3]);/*insert in front of list.chldnodes[3]* * Insert child nodes within the specified node inside the element<ul ID ="List"></ul>

"Note" When assigning a value to a label if it is a double label , such as <span></span>, it is assigned a value of innerHTML or innertext, otherwise such as a single label such as < Input type= "text"/> is assigned as value

(3) Deleting and replacing nodes

The RemoveChild () method removes a node from the document tree. But be assured that the method is not called on the node to be deleted, but rather on its parent node. The method is called on the parent node and the child node that needs to be removed is passed to it as a method parameter. To delete the N node in the document, you can write the code like this:

N.parentnode. RemoveChild (n);

The ReplaceChild () method deletes a child node and replaces it with a new node. The method is called on the parent node, the first parameter is the new node, and the second parameter is the node that needs to be replaced. For example

N.parentnode. ReplaceChild (Document.createelement ("span"), N);
Using DocumentFragment

DocumentFragment is a special node that acts as a temporary container for other nodes. Create a documentfragment like this:

var frag = Document.createdocumentfragment ();

DocumentFragment is independent, not part of any other document. Its parentnode is always null, but similar to element, it can have any number of child nodes, can be used appendchild (), InsertBefore () and other methods to manipulate them.

What's special about it is that it makes a set of nodes look like a node: If you pass a documentfragement to AppendChild (), insertbefore (), or replacechild (), In fact, all the child nodes of the document fragment are inserted into the document, not the fragment itself. Because JavaScript reloads the DOM of the entire document as it operates the DOM, in order to reduce DOM operations, you can put the DOM into documentfragment when you manipulate the DOM (for which you add or remove properties), and finally manipulate the document fragment at once. DocumentFragment can be equivalent to a buffer, when the need to update a large number of DOM nodes, the page will be a lot of rendering, which will greatly reduce performance, so you can use DocumentFragment all the rendered nodes into memory, and finally a one-time rendering, This can reduce the burden on the browser and improve the speed of page rendering.

The following function uses DocumentFragment to sort the child nodes of a node in reverse order:

/*Load DOM tree call function to reverse output*/window.onload=function () {Reverse (document.getElementById ("List")); }function reverse (n) {/*Create a documentfragment as a temporary container*/varf =document.createdocumentfragment ();/*from the back to the front loop child nodes, move each child node to the document fragment. The last node of n becomes the first node of F, which is also Enron. Note that adding a node to F will automatically remove the node from N*/ while(N.lastchild) f.appendchild (n.lastchild);/*Finally, all the child nodes are moved back to N at once .*/N.appendchild (f);}<ul ID ="List"> <li><span><a href ="#">1</a></span></li> <li><span><a href ="#">2</a></span></li> <li><span><a href ="#">3</a></span></li> <li><span><a href ="#">4</a></span></li> <li><span><a href ="#">5</a></span></li> <li><span><a href ="#">6</a></span></li></ul>

(Sixth day) DOM

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.