Home>

domdom is short for document object model. The document object model is a document that uses xml or html in the form of tree nodes.With dom methods and properties,You can visit,Modify, delete any element on the page,You can also add an element.dom is a language-independent API that can be implemented in any language,Of course JavaScript is also included

Take a look at the text below.

<! Doctype html public "-//w3c //dtd xhtml 1.0 strict //en"
  "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html>
 <head>
  <title>my page</title>
 </head>
 <body>
  <p>first paragraph</p>
  <p><em>second</em>paragraph</p>
  <p>final</p>
 </body>
</html>

Let's take a look at the second paragraph

<p><em>second</em>paragraph</p>

You can see that this is a p-tag. It is included in the body tag. So body is the parent of p,p is a child node.The first and third paragraphs are also children of the body.They are all siblings of the second segment.This em tag is a child of the second segment p.Therefore p is its parent node.The parent-child relationship can depict a tree-like relationship.So it is called the dom tree.

core dom and html domWe already know that dom can depict html and xml documents. In fact, the html document is the xml document, but it is more standardized.So as part of dom level 1,The core dom specification is applicable to all xml documents and the html dom specification extends core dom. Of course, html dom cannot be applied to all xml documents, only html documents. Let's take a look at the constructors for core dom and html dom.

Constructor relationship

Visit the dom nodeWhen i want to validate a form or change an image,We need to know how to access the element (element.). There are many ways to get elements.

document nodeThe document allows us to access the current document.We can use firebugs (Firefox plugin) to view the properties and methods of the document.

All nodes have attributes of nodetype, nodename, nodevalue. Let's see what the nodetype of the document is

document.nodetype;//9

There are 12 node types in total.document is 9. Commonly used are element (element:1), attribute (attribute:2), text (text:3).

Nodes also have names.For html tags. The node name is the label name.The name of the text node is #text. The name of the document node is #document.

Nodes also have values.For text nodes,Value is text.document value is null

documentelementxml will have a root node to include the document.For html documents. The root node is the html tag. Visit the root node. You can use the documentelement attribute.

document.documentelement;/<html>
document.documentelement.nodetype;//1
document.documentelement.nodename;//html
document.documentelement.tagname;//For element, nodename and tagname are the same

child nodesIn order to determine whether it contains child nodes, we can use the following method

document.documentelement.haschildnodes ();//true

html has two child nodes.

document.documentelement.childnodes.length;//2
document.documentelement.childnodes [0];//<head>
document.documentelement.childnodes [1];//<body>

Parent nodes can also be accessed through child nodes

document.documentelement.childnodes [1] .parentnode;//<html>

We assign a reference to the body to a variable

var bd=document.documentelement.childnodes [1];
bd.childnodes.length;//9

Let's look at the structure of the body

<body>
 <p>first paragraph</p>
 <p><em>second</em>paragraph</p>
 <p>final</p>
 <!-And that "s about it->
</body>

Why is the number of child nodes 9?

First of all, there are 4 p and 4 comments.

The 4 nodes contain 3 blank nodes.That's seven.

The eighth blank node between the body and the first p.

The ninth is a blank node between the comment and.

A total of 9 nodes.

AttributesBecause the first node is a blank node,So the second node is the first p-tag.

bd.childnodes [1];/<p>

Can see if it has attributes

bd.childnodes [1] .hasattributes ();//true

You can also view the number of attributes

bd.childnodes [1] .attributes.length;//1
//You can use index and name to access attributes,You can also use the getattribute method.
bd.childnodes [1] .attributes [0] .nodename;//class
bd.childnodes [1] .attributes [0] .nodevalue;//opener
bd.childnodes [1] .attributes ["class"]. nodevalue;//opener
bd.childnodes [1] .getattribute ("class");//opener

Accessing the contents of a tagLet's look at the first label p

You can access it with the textcontent property.To be careful of,There is no textcontent in ie browser, please replace it with innertext, the result is the same.

bg.childnodes [1] .textcontent;//"first paragraph"

Another attribute is innerhtml. This is not a specification of dom. But mainstream browsers support this property.It returns html code.

bg.childnodes [1] .innerhtml;//"first paragraph"

The first paragraph has no html code, so the result is the same as textcontent (ie innertext in ie).Take a look at the second paragraph containing the html code

bd.childnodes [3] .innerhtml;//"<em>second</em>paragraph"
bd.childnodes [3] .textcontent;//second paragraph

Another way to get text nodes,Then take the nodevalue attribute, the code is as follows

bd.childnodes [1] .childnodes.length;//1 number of child nodes
bd.childnodes [1] .childnodes [0] .nodename;//node name #text
bd.childnodes [1] .childnodes [0] .nodevalue;//node value first paragraph

Quick access to domYou can access any node in the document through childnodes, parentnode, nodename, nodevalue, and attributes.But in actual application,Text nodes are annoying.If the text changes,May affect the script.And if the dom tree is deep enough,Then it is indeed a bit inconvenient to visit.Fortunately, we can access nodes in a more convenient way.These methods are

getelementsbytagname ()
getelementsbyname ()
getelementbyid ()

First say getelementsbytagname ()

Get a collection of html elements by a tag name.Examples are as follows

document.getelementsbytagname ("p"). length;//3

Because it returns a collection,We can use array subscripts to access or through the item method. For comparison, it is recommended to use an array access method.Simpler.

document.getelementsbytagname ("p") [0];//<p>
document.getelementsbytagname ("p"). item (0);//Same result as above
document.getelementsbytagname ("p") [0] .innerhtml;//first paragraph

Access the element's attributes,You can use attributes collection. But the easier way is to access it directly as a property.See an example

document.getelementsbytagname ("p") [2] .id;//closer

To be careful of,The class attribute cannot be used normally.. Use classname. Because class is a reserved word in the JavaScript specification.

document.getelementsbytagname ("p") [0] .classname;//opener

We can access all elements of the page as follows

<span>document.getelementsbytagname ("*"). Length;//9</span>

Note:The above method is not supported in earlier versions of ie.Can be replaced with document.all. ie7 is already supported,But all nodes are returned, not just element nodes.

siblings, body, first, last childnextsibling and previoussibling are two more convenient ways to access the dom. Used to access adjacent nodes.Examples are as follows

var para=document.getelementbyid ("closer")
para.nextsibling;//"" \ n "
para.previoussibling;//"" \ n "
para.previoussibling.previoussibling;//<p>
para.previoussibling.previoussibling.previoussibling;//"" \ n "
para.previoussibling.previoussibling.nextsibling.nextsibling;//<p>

body is used to access the body element.

document.body;//<body>

firstchild and lastchild. firstchild is the same as childnodes [0]. lastchild is the same as childnodes [childnodes.length-1]

Traversing the domThrough the above learning,We can write a function,Used to traverse the dom

function walkdom (n) {
 do {
  alert (n);
  if (n.haschildnodes ()) {
   walkdom (n.firstchild)
  }
 } while (n=n.nextsibling)
}
walkdom (document.body);//Test

Modify nodeLet's take a look at the modification of the dom node.

Get the node i want to change first.

var my=document.getelementbyid ("closer");

It is very easy to change the attributes of this element.We can change innerhtml.

my.innerhtml="final";//final

Because innerhtml can write html, let's modify the html.

my.innerhtml="<em>my</em>final";/<em>my</em>fnal

The em tag has become part of the dom tree.We can test

my.firstchild;/<em>
my.firstchild.firstchild;//my

We can also change the value through nodevalue.

my.firstchild.firstchild.nodevalue="your";//your

Modify styleMost editing nodes are likely to be modification styles.Element nodes have a style attribute to modify the style.There is a one-to-one correspondence between the style attribute and the css attribute.The following code

my.style.border="1px solid red";

Many css attributes have a dash ("-"), such as padding-top, which is illegal in javascript.In this case, be sure to omit the tilde and capitalize the first letter of the second word.The specifications are as follows. Margin-left becomes marginleft. So on and so forth

my.style.fontweight="bold";

We can also modify other attributes,It doesn't matter if these properties are initialized.

my.align="right";
my.name="myname";
my.id="further";
my;/<p align="right">

Create node

To create a new node,You can use createelement and createtextnode. If the new creation is completed,Nodes can be added to the dom tree using appendchild ().

Create an element p and set the innerhtml attribute

var myp=document.createelement ("p");
myp.innerhtml="yet another";

Element p is completed,You can modify and add attributes at will

myp.style.border="2px dotted blue"

Next you can use appendchild to add new nodes to the dom tree.

document.body.appendchild (myp)

Using domThe innerhtml method is really simple,We can use the pure dom method to achieve the above function.

Create a new text node (yet another) Create a new paragraph Add text nodes to the paragraph. Add paragraph to body
//create p
var myp=document.createelement ("p");
//create a text node
var myt=document.createtextnode ("one more paragraph")
myp.appendchild (myt);
//create a strong element
var str=document.createelement ("strong");
str.appendchild (document.createtextnode ("bold"));
//add strong element to p
myp.appendchild (str);
//add the p element to the body
document.body.appendchild (myp);
//Result<p>one more paragraph<strong>bold</strong></p>
 clonenode ()

Another way to create a new node is,We can use clonenode to replicate a node.clonenode () can be passed a boolean parameter. If true is deep copy,Including his children,false, just copy yourself.

First get the element to be copied.

var el=document.getelementsbytagname ("p") [1];//<p><em>second</em>paragraph</p>

No deep copy first.

document.body.appendchild (el.clonenode (false))

We found that the page has not changed,Because only the element p is copied. Same effect as below.

document.body.appendchild (document.createelement ("p"));

If you use deep copy,All child nodes including p will be copied.Including text nodes and em elements, of course.

document.body.appendchild (el.clonenode (true))

insertbefore ()Appendchild is to add the element to the end.The insertbefore method can more precisely control the position of the inserted element.

elementnode.insertbefore (new_node, existing_node)

Examples

document.body.insertbefore (
 document.createtextnode ("boo!"), document.body.firstchild
);

Means creating a new text node,Think of it as the first node of the body element.

Delete node

To delete a node from the dom tree,We can use removechild (). Let's take a look at the html to be manipulated

<body>
 <p>first paragraph</p>
 <p><em>second</em>paragraph</p>
 <p>final</p>
 <!-And that "s about it->
</body>

Take a look at the following code,Delete the second paragraph

var myp=document.getelementsbytagname ("p") [1];
var removed=document.body.removechild (myp);

A removed node is a removed node.You can also use this deleted node later.

We can also use the replacechild () method. This method is to delete a node,And replace it with another node.After performing the last delete node operation,The result is as follows

<body>
 <p>first paragraph</p>
 <p>final</p>
 <!-And that "s about it->
</body>

Let's take a look at the use of replacechild. We replace the previous p with the previous deleted node

var replaced=document.body.replacechild (removed, p);

Same as removeChild returns.replaced is the removed node.Now the result is

<body>
 <p>first paragraph</p>
 <p><em>second</em>paragraph</p>
 <!-And that "s about it->
</body>
  • Previous Yii Timing Examples
  • Next Analysis of the difference between C ++ front and back