It's easy to tell, Dom.

Source: Internet
Author: User
Tags return tag

Dom is all front-end development every day to deal with things, but with the advent of jquery and other libraries, greatly simplifying the DOM operation, resulting in people slowly "forget" its original appearance. However, in order to learn the front-end knowledge, the understanding of the DOM is indispensable, so this article tries to explain the system of DOM related knowledge, if there are omissions or errors, please also point out the discussion ^ ^.

First, what is DOM?

The DOM (Document Object model) is an API for HTML and XML documents that can be changed by DOM.

This is an official statement, and you certainly don't understand.

For example: We have a piece of HTML, so how to access the second layer of the first node, how to move the last node above the first node?

The DOM is the standard that defines what should be done if you do something similar. For example, use getElementById to access nodes, and use InsertBefore to insert nodes.

When the browser loads HTML, the corresponding DOM tree is generated.

In short, Dom can be understood as an implementation standard for accessing or manipulating HTML various tags.

For an HTML, the document node documents (invisible) is its root node, and the corresponding object is the Document object (strictly speaking subclass HTMLDocument object, which will be noted when describing the document type separately).

In other words, there is a document node, documents, and then it has child nodes, such as through document.getElementsByTagName ("HTML"), the type is the element node elements HTML.

Each piece of HTML markup can be represented by a corresponding node, for example:

An HTML element is represented by an element node, a comment is represented by a comment node, a document type is represented by a document type node, and so on.

There are 12 types of nodes defined, all of which inherit from node type.

So we'll start with the node type, because this type of method is inherited by all nodes.

Second, node type (base class, all nodes inherit its method)

node is the base type for all nodes, and all nodes inherit from it, so all nodes have some common methods and properties.

The properties of node type are first spoken

The first is the NodeType attribute, which is used to indicate the type of node, for example:

Document.nodetype;    // returns 9, where the document object is an instance of documents node

In this, 9 represents the meaning of the Document_node node, you can view the number of nodes by Node.document_node

Document.nodetype = = = Node.document_node;    // true

As for the total number of nodes, each node corresponds to how much, this can ask Google to know. The usual thing is that element node elements (corresponding numbers are 1) and text nodes (corresponding numbers are 3).

And then the usual nodename and nodevalue.

For element node nodename is the tag name, NodeValue is null

For text nodes nodename "#text" (tested in chrome), NodeValue is the actual value

Each node also has the ChildNodes attribute, which is a very important property that holds all the immediate child elements of this node

Call ChildNodes return is a NodeList object, it is extremely like an array, but there is one of the most critical place, it is dynamic query, that is, each call it will query the structure of the DOM, so it needs to be cautious, pay attention to performance.

Access ChildNodes can use the following table or Item method of the array

Then there are various properties of each node that allow them to access each other, which summarizes the

More useful methods and properties:

1, HasChildNodes ()

Returns true if the containing child node is simpler than the length of the query childnodes.

2, Ownerdocument

Returns a reference to the document node (in HTML, which is the documents object)

Then introduce the common methods of node type

The AppendChild () method can add a node at the end of the node's childnodes, and it's worth noting that if the node is already in the document, it will delete the original node and feel like a moving node.

The InsertBefore () method accepts two parameters, one is the inserted node and the other is the referenced node. If the second argument is null, the InsertBefore and appendchild effects are the same. Otherwise, the node is inserted before the reference node. It is important to note that if the second argument is not NULL, then the inserted node cannot be a node that already exists.

The ReplaceChild () method can replace a node, accept two parameters, require the inserted node, and the node that needs to be replaced. Returns the node that was replaced.

RemoveChild () removes the node. There is a common need, such as I have a node #waste-node, so how to remove it?

var wastenode =  document.getElementById ("Waste-node"); WasteNode.parentNode.removeClhid ( Wastenode);     // get the parent node first, then call Removeclild to delete yourself

Here to pause for a moment, do not know that you notice no, the above several methods are operating a node of a child node, that is, before the operation must find the parent node (through ParentNode to find)

Next, the method of copying nodes:

CloneNode (); Copy node, accept a parameter of true or FALSE. If true is to replicate that node and its child nodes. If False, the node itself is copied (the copied node will not have any child elements). This method returns the copied node, and if you need to manipulate it, you need to use the previous 4 methods to put the node into HTML.

At this point, the common properties and methods of the node type are all gone. All node types are inherited from node types, so they are all nodes.

Iii. type of document

The document type was mentioned at the very beginning of what the DOM was about. In fact, the most important thing about this type is that one of its subclasses HTMLDocument has an instance object document. And this document object is one of our most used objects.

The document object is also mounted on the Window object, so the document can be accessed directly from the browser.

The usual way to talk about the properties of the document object is to talk about it.

Some properties on the Document object

Document.childnodes inherits from the node type described above and can return direct child nodes of the document (usually including document declarations and HTML nodes)

Document.documentelement can get a reference to the HTML node directly (equivalent to document.getElementsByTagName ("HTML") [0]).

Document.body a reference to the body node

Document.title page title, can be modified, will change the name on the browser tag

Document. URL of the URL page

Document.referrer get referrer, that is, open this page of the address of the page, do source statistics time is more useful

Document.domain Gets the domain name, can be set, but usually can only be set to not include sub-domain name, in some subdomains in the case of cross-domain valid.

The following two familiar methods are introduced

getElementById and getElementsByTagName

getElementById, passing in the ID, gets the element node. The parameters inside are case-sensitive (ie8-not differentiated). Note: If there are multiple elements with the same ID, the first one is returned . the name of the form element inside the ie7-is also used as the ID.

getElementsByTagName gets the element according to the tag, and the htmlcollection type is obtained. If "*" is passed in, all elements can be obtained.

There is also a method that only the HTMLDocument type (that is, the Document object) Getelementsbyname, as the name implies, returns the element according to name.

The Document object also has some collections, such as document.forms, which can return all form forms. The type is also htmlcollection.

Speaking of Htmlcollection, just say it again.

Htmlcollection is a collection that contains one or more elements, and the nodelist is quite similar to the one above. Htmlcollection This type has two methods, one is to get concrete elements by subscript (or. Item ()), and to get concrete elements by [' name '] (or. Nameditem ()).

Finally, there is a set of important methods for the document object, that is

Write () Writeln () open () Close ()

Open and close are the output streams for opening and closing Web pages, which are equivalent to the open State during page loading. These two methods generally do not use it.

Then the important way is write and Writeln, which are written to the page, the difference is that the latter will add a newline character more.

Note: During page loading, you can use both methods to add content to the page. If the page is already loaded and then called write, the entire page is rewritten.

Also, if you want to dynamically write scripts such as <script>xxx</script>, then pay attention to the </script> separate to assemble, otherwise it will be mistaken for the script end of the flag, Causes this terminator to match to the above one start character. Can write "<SCR" + "ipt>";

Iv. type of element

Let's talk about the most important and most common type, element type.

What we do every day is the element type (essentially HtmlElement, which is easy to understand, so to speak), such as

The element type is returned. What we call "Dom objects", often referred to as the object of element type.

Then talk about the common properties of this type:

First of all, the attribute methods on the node type are all there, and this one is no longer repeated, but mainly about its own uniqueness.

The first is tagname, which is the same as the NodeName inherited from node type. is the return tag name, usually uppercase, and the result depends on the browser. So I'm doing a comparison.

It is best to call the next similar toLowerCase () method to do the comparison.

Tell me about the HtmlElement types mentioned above.

The HtmlElement type inherits from the element type and is the actual type of the HTML element, and the elements we use in the browser are all of this type.

This type has some standard properties, such as:

Unique identification of the ID element

Title is usually the information that will be displayed when the mouse is moved up

ClassName class Name

And so on, these properties are read-write, which means that you change them to get a corresponding effect.

In addition to attributes, there are several important methods

First, the method of manipulating node properties

GetAttribute, SetAttribute, RemoveAttribute these 3 methods.

These are the most commonly used methods of operation properties, how to use not to say, very simple, as the name implies.

There is also a attributes property that holds all the attributes of the element.

Stop here, there is a question, Ele.classname and Ele.getattribute ("class") return the result is not the same thing?

To answer this question, I would like to say an important point of knowledge, the attribute structure of an element, such as a INPNT element

<id= "Test"  checked= "Checked">

Then the attributes of this element are included in the input.attributes, such as the class, ID, or data-test that you see on the HTML element.

Then GetAttribute, SetAttribute, removeattribute These 3 methods can be considered as a quick way to take the attributes collection. Direct input.id or input.classname are directly linked to input properties, and attributes are peers. so the return of things may look like the past, the actual is not the same, do not believe you can try input.checked this input.getattribute ("checked") try.

About this knowledge point, the detailed said can write another article, in my blog from IS (": Checked") talk about, you can look at this article and the discussion after the article, you can know how it is.

In general, these 3 methods typically use a custom property, rather than an "acknowledged feature" such as ID, class, and so on.

Now, let's talk about creating elements

Document.createelement () can create an element, such as:

Document.createelement ("div");

In general, you can set properties for the element, two methods, one is direct Node.property can also Node.setattribute ("PropertyName", "value"). such as

But after all this, this element is still not on the page, so you have to add the elements to the page by using the above-mentioned methods like AppendChild.

In IE, you can also go through the entire HTML string to create elements, such as

Document.createelement ("<div>test</div>");

Finally, element nodes also support HTMLDocument types of lookup methods, such as getElementsByTagName. But it will only find the nodes of its own offspring. So you can write code like this.

document.getElementById ("Test"). getElementsByTagName ("div");    // Locate all DIV nodes under the ID test element

V. Type of text

This type is very special and is the third most common type (the first and second are document and element).

This node is simply a string.

One important feature is that it has no child elements (but this is also known as a careful thought = =)

Access the text content of a text node, either through the NodeValue or the Data property.

Here's a brief talk about some of the ways it provides

AppendData ();    // Add content DeleteData at the end of text (offset, count);    // Remove count characters from the position specified by offset

There are insertdate, ReplaceData, Splittext and other methods, do not say, the opportunity to use a little, you can use the time to review.

Then it also has a lenght property that returns the length of the character.

Here says a common pit. For example, the following HTML structure

< ul >     < Li ></ Li >     < Li ></ Li > </ ul >

Here, what is the first sub-node of UL (FirstChild)? At first glance, it must be Li, but in fact, you will find not Li, but a text node!

This is because the browser thinks that there is a white-space character between the UL and the first Li, so there is a text node.

Here a common problem is to traverse the UL childnodes, the elements must be determined to determine whether the next nodetype is equal to 1(equals 1 is the element node), so as to skip the pit. Otherwise you can delete all the spaces and line breaks.

The way to create a text node is document.createTextNode

Next, as with the element type, it is then inserted into the elements, which the browser can see.

Vi. some other types of Comment, DocumentType and DocumentFragment

These infrequently used words have taken

Comment is a comment node

DocumentType is the DOCTYPE node, accessed through Docment.doctype.

DocumentFragment This node is a document fragment that is occasionally used.

A common use, for example, is to insert 3 Li in a ul.

If you loop 3 times, the browser will render 3 times, which has a pretty big impact on performance.

So that's what people do.

First

var fragment = Document.createdocumentfragment ();

Then loop the LI, insert the appendchild into the fragment.

At the end of the fragment inserted into the UL inside. That's going to be quick.

Vii. DOM Extensions

In the above mentioned so many node types, presumably you have a very deep understanding of the DOM node, the following is about the DOM extension of some things.

The browser expands some DOM functionality for the convenience of developers.

Because the browser expands itself, it is important to note the compatibility issues before use

Judging "standard mode" and "Promiscuous mode" through Document.compatmode and new Document.documentmode

This is not a text node as the first sub-element of the pit, so the browser implemented a children property, which contains only the element node.

To make it easier to determine if a node is a sub-node of B-node, A contains method is introduced, such as

B.contains (A);    // true means yes, false represents not

This method has compatibility issues and can be solved by Google before use.

4 method innertext/innerhtml/outertext/outerhtml are provided for access elements.

Through these methods, elements can be read and written.

Where *text is the return text content *html is the return HTML text.

The outer*, however, represents whether the element itself is included.

In actual use, there is no difference between inner* and outer* when reading content.

When you write content to an element, it is the difference between the elements themselves.

Importantly, these methods have performance problems, such as in IE, the node that is deleted through inner*, its bound event is still in memory, it is very easy to consume a lot of memory.

Another trick is to insert a lot of HTML code, which is very fast with innerHTML, and is recommended for use.

Viii. Summary

First of all, thanks to all the friends who have seen here, haha, there are too many things about DOM, but this is one of the most important front-end knowledge points. The article is long, maybe a bit dull, but I hope you can have a good patience after reading ^ ^.

My notes have been updated again, this time mainly updated a mobile Page page development method, you can go to see ^ ^.

Reproduced this site article please indicate the author and the source of exotic flowers –http://www.cnblogs.com/season-huang/, do not use for any commercial use

It's easy to tell, Dom.

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.