Dom manipulation of JavaScript

Source: Internet
Author: User

Directory:

1. Introduction and classification of DOM

2. Fetching of DOM elements

3. Document structure and traversal

3.1 Node Relationship

3.2 Element Relationships

3.2 Traversal

4. Operation of the node

4.1 Creating and inserting nodes

4.2 Deleting a node

4.3 Replacing nodes

5. Summary

  1. Introduction of DOM and classification of nodes

The full name of DOM is the Document Object model, which is a standard programming interface recommended by the organization to handle extensible flag languages.

The DOM is actually a document model that is described in an object-oriented manner. The DOM defines the relationships between the objects that are required to represent and modify the document, the behavior of the objects, and the property-level objects. We can think of the DOM as a tree representation of the data and structure on the page, but the page is not actually implemented in this tree way.

  

Each ingredient in the dom,html document is a node:

1) The entire document is a document node;

2) Each HTML tag is an element node;

3) text that is contained in an HTML element is a text node;

4) An attribute node for each HTML attribute.

More specifically, we refer to the table:

Type Value Description Common
Element_node 1 ELEMENT node *
Attribute_node 2 Attribute node *
Text_node 3 Text node *
Cdata_section_node 4 CDATA section
Entity_reference_node 5 Entity reference
Entity_node 6 Entity
Processing_instruction_node 7 Processing instructions
Comment_node 8 Comment Node *
Document_node 9 Document node *

How to use:

<DivID= "Main"></Div><Scripttype= "Text/javascript">    varMain=document.getElementById ("Main"); Console.log (Main.nodetype==node.element_node);</Script>

However, it is important to note that node and Element_node are not supported in IE8 and the browsers below, but are supported for numeric types, while Chrome, FF, and IE9 support both node and number types. So the compatibility should be written like this:

<DivID= "Main"></Div><Scripttype= "Text/javascript">    varMain=document.getElementById ("Main"); Alert (Main.nodetype== 1);</Script>

  2. Fetching of DOM elements

Dom elements are obtained in a number of ways, commonly used: getElementById (ID), Getelementsbyname (name), getElementsByTagName (tag), and so on.

Through the code we can understand how they are used:

<!DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"Xml:lang= "en"><Head>    <Metahttp-equiv= "Content-type"content= "Text/html;charset=utf-8">    <title>Document</title></Head><Body>    <DivID= "Main">        <DivID= "First"class= "List">            <P>First_p</P>            <P>First</P>            <P>First</P>        </Div>        <DivID= "Second"class= "List">Second</Div>        <DivID= "Third"class= "List">            <inputtype= "text"name= "username" />        </Div>    </Div></Body><Scripttype= "Text/javascript">    //get elements by ID    varMain=document.getElementById ("Main");    Console.log (main); //get elements by name    varusername=Document.getelementsbyname ("username");    Console.log (username); //get elements with HTML tag names    varP=document.getElementsByTagName ("P");    Console.log (P); //get elements by class    varList=Document.getelementsbyclassname ("List"); Console.log (list);</Script></HTML>

Execution Result:

  

There are four ways to get DOM elements by using different parameters, but it's a bit of a difference: document.getElementById (ID) returns a DOM element or undefined (when the ID doesn't exist) , and the following three methods are returned as an array, and if the element does not exist, the array is empty, not undefined. It is also necessary to note that: Document,getelementsbyclassname (Class) is a HTML5 in the existence of a API,IE8 and the following browser is not able to use this method.

At the same time, the selectors API provides two core methods: Queryselector () and Queryselectorall ().

The Queryselector () method receives a CSS selector, returns the first element that matches the pattern, or null if no matching element is found. If an unsupported selector is passed in, the method throws an error.

 //  get BODY element   body = Document.queryselector ("Body"  //  var  main = Document.queryselector ("#main"  //  Gets the first element of the class named List  var  list = Document.queryselector (". List"  //  var  div = main.queryselector (". List"  

The way to get DOM elements is very much like jquery, get the tag element into the tag, follow the ID of the incoming #id, according to the class gets passed in. class! When you call the Queryselector () method through the document, the matching elements are found in the scope of the documents element. When the method is called through an element, it is only found in the descendant elements of the element.

The Queryselectorall () method is the same as the Queryselector () method, but the method returns all matching elements, the returned type is an array, and if there are no matching elements, the array is empty.

  3. Document structure and traversal

  3.1 Node Relationship

1) ParentNode Gets the parent node of the node
2) ChildNodes gets the array of child nodes of the node
3) FirstChild Gets the first child node of the node
4) LastChild Gets the last child node of the node
5) NextSibling Gets the next sibling element of the node
6) Previourssibling Gets the previous sibling element of the node

var first = Document.queryselector ("#first"); Console.log (First.parentnode, First.childnodes, First.firstchild);

We can call different methods to get the nodes of each critical node.

In this way, all the node types in the 1th table can be obtained, such as text nodes, but sometimes we just want to get the element nodes, not the other nodes, and we use the element traversal.

  3.2 Element Relationships

1) firstelementchild first child element node
2) Lastelementchild the last child element node
3) nextelementsibling Next sibling element node
4) previouselementsibling before a sibling element node
5) Childelementcount number of child element nodes

These elements do not have to worry about blank text nodes, making it easier to find DOM elements. Browsers that support these elements have ie9+,firefox3.5+,safari4+,chrome and opera10+.

  3.3 Traversal

Based on the methods provided above, we are able to traverse elements in the document, such as outputting all of the node's subnodes, outputting the depth of the node as the root node, and so on.

  4. Operation of the node

Operations on nodes include: Create, INSERT, delete, replace, and so on.

  4.1 Creating and inserting nodes

There are two ways to create a node: One is to create a text node, and the other is to create an element node. As follows:

document.createTextNode (text); Create a text node

Document.createelement (ele); Create a node of an element

There are two ways to insert a node: At the end of the child node of the node, insert it in front of a node

AppendChild (node); Insert to the end of the child node

Insetbefore (node[, org]); Inserted in front of the org node, if the org node is empty, then the function functions like appendchild (node)

To see this more visually, I added the border and margin two CSS properties to the div above. This is true when no changes are made to the node:

The outermost border is #main, and the border where the input box is is #third.

  

Now perform the insert operation for the node:

varMain = Document.queryselector ("#main");varSecond = Document.queryselector ("#second");//Create a text nodevarText = document.createTextNode ("Hello world!!");//Creating ELEMENT Nodesvarforth = document.createelement ("div"); Forth.id= "Forth"; Forth.classname= "List"; forth.innerhtml= "Forth";//at the end of the Add text nodemain.appendchild (text);//add forth in front of secondMain.insertbefore (forth, second);

Now the page is like this:

  

Now we can see: Hello world!! Added to the end of the #main, #forth添加到了 the front of the #second.

  4.2 Deleting a node

Parentnode.removechild (node); Delete the child node of parentnode.

For example, if we want to delete #main's child node #second, then we can:

var main = Document.queryselector ("#main"); var second = Document.queryselector ("#second"); Main.removenode (second);

It's so easy!

  4.3 Replacing nodes

Parentnode.replacechild (Node1, Node2); Delete the child node Node1 and replace it with a new node Node2

  5. Summary

In fact, there is a lot of knowledge about DOM objects, here is a simple summary of knowledge

  

Reference:

  Http://www.cnblogs.com/kissdodog/archive/2012/12/25/2833213.html

Dom manipulation of JavaScript

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.