The basics of accessing, creating, modifying, and deleting DOM nodes in JavaScript

Source: Internet
Author: User
Tags code tag html code tag tag name

Dom
DOM is the abbreviation for Document Object model. The Document Object model is a document that takes XML or HTML as the representation of a tree node. With Dom methods and properties, you can access, modify, delete any element on the page, and you can add an element. Dom is a language-independent API that can be implemented by any language, including, of course, JavaScript
Look at one of the following text.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" 
  "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-STRICT.DTD" > 
 
 


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 the body is the parent of P, and P is a child node. The first and third paragraphs are also child nodes of the body. They are both sibling nodes of the second paragraph. This EM tag is a sub node of the second paragraph p. So P is its parent node. A parent-child node relationship can depict a tree-like relationship. So it's called the DOM tree.

Core Dom and HTML Dom
we already know that the DOM can paint HTML and XML documents. In fact, HTML documents are XML documents, but more canonical. So as part of DOM Level 1, the core DOM specification extends the core DOM to all XML documents and the HTML DOM specification. Of course, HTML DOM does not apply to all XML documents, only to HTML documents. Let's look at the constructors for the core DOM and the HTML DOM.

Constructor Relationship

accessing DOM nodes
before you verify the form or replace the picture, we need to know how to access the elements (element.). There are many ways to get elements.

Document node
we have access to the current documentation through document. We can view the properties and methods of the document via Firebugs (Firefox plugin).

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

Document.nodetype;//9 

A total of 12 node types. Document is 9. Commonly used are elements (element:1), Attributes (Attribute:2), text (Text:3).
The node also has a name. For HTML tags. The node name is the label name. The name of the text node (literal) is #text. The name of the Documents node (document) is #document.

The node also has a value. For text nodes, the value is the text. The value of document is NULL

documentelement
XML will have a root node to package the document to include. For HTML documents. The root node is the HTML tag. Access the root node. You can use the DocumentElement property.

document.documentelement;// 
 


Child Nodes
to determine if a child node is included we can use the following method

Document.documentElement.hasChildNodes ();//true 

HTML has two child nodes.

DOCUMENT.DOCUMENTELEMENT.CHILDNODES.LENGTH;//2 
 
document.documentelement.childnodes[0];// 
 

You can also access the parent node through child nodes

Document.documentelement.childnodes[1].parentnode;// 
 

We assign the body reference to the variable

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

Let's look at the body structure.

<body> 
 <p class= "opener" >first paragraph</p> 
 <p><em>second</em> paragraph</p> 
 <p id= "Closer" >final</p> 
 <!--and that ' s about it--> 
</body >


Why the number of child nodes is 9.
First, there are 4 p and a total of 4 comments.
The 4 nodes contain 3 blank nodes. This is 7.
The 8th is a blank node between the body and the first p.
The 9th is a blank node between the annotation and the </body>.
Altogether 9 nodes.

Property
because the first node is a blank node, the second node is the first P tag.

bd.childnodes[1];//  <p class= "Opener" > 

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 
 
//can use index and name to access the property, or you can 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 the tag
Let's take a look at the first label P
You can use the Textcontent property to access it. Note that in IE browser does not exist textcontent, please use innertext to replace, the result is the same.

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

Another attribute is innerHTML. This is not a specification of the DOM. But this property is supported by mainstream browsers. It returns the HTML code.

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

The first paragraph has no HTML code, so the result is the same as textcontent (ie is innertext). Take a look at the second paragraph that contains the HTML code tag

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


Another way to get the text node and then take the NodeValue property, 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 of the paragraph 


Quick access to DOM
with Childnodes,parentnode,nodename,nodevalue and attributes, you can access any node in the document. But in the actual application process, the text node is more annoying. If the text changes, it can affect the script. And if the DOM tree is deep enough, it's really inconvenient to visit. Luckily we can access the nodes in a more convenient way. These methods are

getElementsByTagName ()
getelementsbyname ()
getElementById ()

First of all, getElementsByTagName ()
Gets a collection of HTML elements through a tag name (tag name). Examples are as follows

document.getElementsByTagName (' P '). LENGTH;//3 

Because the return is a set, we can access or pass the Item method in the form of a subscript in several groups. It is also recommended to use array access methods. A little bit simpler.

document.getElementsByTagName (' P ') [0];//<p class= "opener" > 
document.getelementsbytagname (' P '). Item (0) ;//As the result above 
 
document.getelementsbytagname (' P ') [0].innerhtml;//first paragraph 


To access the attributes of an element, you can use a attributes collection. But the simpler approach is to simply access the line as a property. See an example

document.getElementsByTagName (' P ') [2].id;//closer 

Note that the class attribute is not used properly. To 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 in the following ways

<span style= "color: #ff0000;" >document.getelementsbytagname (' * ') .length;//9</span> 

Note: This method is not supported in earlier versions of IE. Can be replaced with document.all. IE7 has been supported, but it returns all nodes (node), not just the element nodes.


siblings, body, the last child
nextsibling and previoussibling are two more convenient ways to access the DOM. That is 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 id=" Closer "> 


The body is used to access the BODY element.

Document.body;//<body> 

FirstChild and LastChild. FirstChild is the same as childnodes[0]. LastChild and Childnodes[childnodes.length-1].

Traverse Dom
through the above study, we can write a function to traverse the DOM

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

modifying nodes
Here's a look at the changes to the DOM node.
Get the node you want to change first.

var my = document.getElementById (' Closer '); 

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

my.innerhtml = ' final ';//final 

Because innerHTML can write to HTML, we modify the HTML.

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

EM tags have become part of the DOM tree. We can test it.

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

We can also change the value by NodeValue.

My.firstChild.firstChild.nodeValue = ' your ';//your 


Modify Style
Most of the modification nodes may be a modified style. The element node has a style attribute used to modify styles. The properties of style and CSS properties are one by one corresponding. The following code

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

Many CSS attributes have dashes ("-"), such as Padding-top, which are illegal in JavaScript. In this case, you must omit the twists and turns the first letter of the second word in uppercase, the specification is as follows. Margin-left into MarginLeft. So

My.style.fontWeight = ' bold '; 

We can also modify other properties, regardless of whether they are initialized or not.

My.align = "right"; 
My.name = ' myname '; 
My.id = ' further '; 
My;//<p id= "Further" align= "right" style= "border:1px solid red;" Font-weight:bold; " > 


Creating nodes

In order to create a new node, you can use createelement and createTextNode. If you create a new completion, you can add nodes to the DOM tree with AppendChild ().
Create an element p and set the innerHTML property

var myp = document.createelement (' P '); 
myp.innerhtml = ' yet another '; 


Element p is complete, you can modify the Add attribute at will

Myp.style.border = ' 2px dotted blue ' 

Next you can add the new node to the DOM tree with AppendChild.

Document.body.appendChild (MYP) 


ways to use the DOM
using the 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
    • Adds a text node to the paragraph.
    • Add a paragraph to the 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 the strong element to P- 
myp.appendchild (str); 
Add the P element to the body 
document.body.appendChild (MYP); 
Results <p>one more paragraph<strong>bold</strong></p> 
 CloneNode ()

Another way to create a new node is to use CloneNode to replicate a node. CloneNode () can pass in a Boolean parameter. If True is a deep copy, including his child nodes, false, just copy yourself.

Gets the element to be copied first.

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

Do not use deep copy first.

Document.body.appendChild (El.clonenode (false)) 

We found that the page did not change because only the element P was copied. The same as the following effect.

Document.body.appendChild (document.createelement (' P ')); 

If you use a deep copy, all of the following child nodes, including p, will be copied. Of course, it includes text nodes and EM elements.

Document.body.appendChild (El.clonenode (True)) 


InsertBefore ()
with AppendChild, the element is added to the end. The InsertBefore method can more precisely control the position of the inserted element.

Elementnode.insertbefore (New_node,existing_node) 

Instance

Document.body.insertBefore ( 
 document.createtextnode (' boo! '), 
 document.body.firstChild 


It means creating a new text node and taking it as the first node of the BODY element.


Delete a node

To remove a node from the DOM tree, we can use RemoveChild (). Let's take a look at the HTML to manipulate

<body> 
 <p class= "opener" >first paragraph</p> 
 <p><em>second</em> paragraph</p> 
 <p id= "Closer" >final</p> 
 <!--and that ' s about it--> 
</body > 

Take a look at the code below and delete the second paragraph.

var myp = document.getelementsbytagname (' P ') [1]; 
var removed = Document.body.removeChild (MYP); 

The removed node is the deleted node. You can also use this to delete the 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 class= "opener" >first paragraph</p> <p id= " 
 Closer" >final</p> 
 <!--and that ' s about it--> 
</body> 

Let's look at the use of replacechild. We replace the last deletion node with the second p.

var replaced = Document.body.replaceChild (removed, p); 

and RemoveChild return the same. Replaced is the node that is removed. Now the result is

<body> 
 <p class= "opener" >first paragraph</p> 
 <p><em>second</em> Paragraph</p> 
 <!--and that ' s about it--> 
</body> 

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.