17.DOM Foundation

Source: Internet
Author: User

Dom


Learning Essentials:
1.DOM Introduction
2. Find elements
3.DOM node
4. Node operation

The DOM (Document Object model) is an API (application interface) for HTML and XML documents. Dom
Depicts a hierarchical node tree that runs a developer to add, remove, and modify portions of a page. Dom is born out of Netscape and Microsoft
The company initiated DHTML (Dynamic HTML), but now it has become a truly cross-platform, language-neutral way of showing and manipulating page markers.

First, the DOM introduction
The three letters in the DOM, D (documents) can be understood as the entire Web page document loaded: O (objects) can be understood as a Window object like
Things like, you can call properties and methods, here we're talking about the document object; M (model) can be understood as a tree structure of a Web page document.

Dom has three levels, namely DOM1, DOM2, DOM3, and DOM1 became the world's standard in October 1998. DOM1 Branch of the
Browsers include ie6+, Firefox, Safari, Chrome, and opera1.7+.

All DOM objects in Ps:ie are implemented in the form of COM objects, which means that the DOM in IE may have some
Difference.

1. Node
When loading an HTML page, the Web browser generates a tree structure that represents the internal structure of the page. The DOM understands this tree structure as a node
Composition
Node tree
Html
|-----------------------------------|
Headbody
|------------------|| ----------|----------|
Metatitle H1pul
|---------|---------|
Li Li Li
From the tree structure above, we understand several concepts, HTM tags without fathers, no brothers, so the HTML tag is the root tag, the head tag is
HTML sub-tags, meta and title tags are sibling relationships. If each label is treated as a node, then these nodes are combined into a
Tree node.

PS: We often refer to labels as elements in the back, which is a meaning.

2. Node types; Element nodes, text nodes, attribute nodes.

<div title = ' attribute node ' > Test div</div>
ELEMENT node
Div
|------------------------|
Title= ' tag Properties ' Test div
Attribute node text node
PS: Nodes are divided into three categories
1. Element node: In fact, it is the label,<div></div>
2. Text node: is actually the plain text inside the tag, test div
3. Attribute node: is actually the attribute of the tag, id= ' box '

Second, find the element

The getElementById provides a convenient and simple method and properties for locating nodes, so that we can operate the nodes quickly, namely: (),
getElementsByTagName (), Getelementsbyname (), getattribute (), SetAttribute (), and RemoveAttribute ().

Element Node method
Method description
getElementById () Gets the node for a specific ID element
Getelementstagname () Gets a list of nodes of the same element
Getelementsbyname () Get a list of nodes of the same name
GetAttribute () Gets the value of a specific element node property
SetAttribute () Sets the value of a specific element node property
Removeattribure () Remove specific element node properties


1.getElementById () method
getElementById () method, takes a parameter: Gets the ID of the element. If the corresponding element is found, the element's Htmldivelement object is returned.
If it does not exist, NULL is returned.

document.getElementById (' box ');//Get the element node with ID box

PS: The above example, by default, returns NULL, regardless of whether there is a id= "box" label, but the execution order problem, the workaround:
1. Move the script call tag to the end of the HTML
2. Use the OnLoad event to handle JS, wait for the HTML to load and then load JS in the OnLoad event.

Window.onload = function () {//pre-loading HTML execution
var box = document.getElementById ("box");
alert (box);
}


Ps:id represents the uniqueness of an element node and cannot create the same named ID for two or more than two element nodes at the same time. Some versions of
The browser will not recognize the getElementById () method, such as IE5.0, then need to make some judgments, can be combined with the browser detection in the previous chapter to
For
if (document.getElementById) {//Determine if getElementById is supported
Alert ("Current browser supports getElementById");
}
Specific judgment code:
Window.onload=function () {
if (document.getElementById) {//Determine if getElementById is supported
var box = document.getElementById ("box");
alert (box);
}else{
Alert ("Current browser does not support getElementById");
}
}

When we get to a particular element node through getElementById (), we get the node object, and through this node object,
We can access a range of its properties.

Element Node Properties
Property Description
TagName gets the label name of the element node
innerHTML gets the text content in the element node, non-w3cdom specification

document.getElementById (' box '). Tagname;//div
document.getElementById (' box '). innerhtml;//Test Div


Properties of HTML Properties
Property Description
ID element Node ID name
Title element node's Title property value
STYLECSS Inline Style property values
Class of the CLASSNAMECSS element

document.getElementById (' box '). id;//get ID, this element node id attribute value, note not attribute node
document.getElementById (' box '). id = ' person ';//Set ID

document.getElementById (' box '). title;//gets the title, gets the value of the title property
document.getElementById (' box '). title = ' title ';//Set title

document.getElementById (' box '). style;//Get Cssstyledeclaration Property Object
document.getElementById (' box '). style.color;//gets the value of the color property in the Style Property object
document.getElementById (' box '). Style.color = ' red ';//Set the value of the color property in the Style Property object

document.getElementById (' box '). classname;//gets the value of the class property
document.getElementById (' box '). className = ' box ';//Set class

The above is a direct call to the HTML attribute, followed by several ways of calling
Alert (document.getElementById (' box ') BBB);//Gets the value of the custom attribute, non IE does not support


2.getElementsByTagName () method
The getElementsByTagName () method returns an array of objects html.collection (NodeList), which holds all the same elements
The list of nodes for the vegetarian name.

document.getElementsByTagName (' * ');//Get all elements
Firefox firebug automatically creates a div after it is opened, so the number of elements is added to all elements.
IE browser than Firefox and Google one more node, is the <! document declaration also counted in >

Ps:ie browser When using wildcards, the canonical declaration of the first HTML of the document is treated as an element node.

document.getElementsByTagName (' Li ');//Gets all LI elements, returns an array
document.getElementsByTagName (' li ') [0];//gets the first LI element, htmllielement
document.getElementsByTagName (' li '). Item (0);//Gets the first LI element, htmllielement
document.getElementsByTagName (' Li '). length;//gets an array of all LI elements
document.getElementsByTagName (' body ') [0];//Gets the body node

PS: Whether getElementById or getElementsByTagName (), when passing parameters, not all browsers must have a zone
Case-sensitive, in order to prevent unnecessary errors and trouble, we must insist on the habit of distinguishing between case and case.


3.getElementsByName () method
The Getelementsbyname () method can get an element of the same name, returning an array of objects htmlcollection (NodeList).
Document.getelementsbyname (' add ');//Get INPUT element
Document.getelementsbyname (' Add ') [0].value;//gets the value of the INPUT element
Document.getelementsbyname (' Add ') [0].checked;//gets the checked value of the INPUT element

PS: For a property that is not HTML-valid, there will be differences in the compatibility of JS acquisition, IE supports its own valid Name property
, and there is an incompatibility problem that is illegal.

4.getAttribute () method
The GetAttribute () method will get the value of the property of an element in the element, and it differs from the method of getting the property value directly using the property.
document.getElementById (' box '). getattribute (' id ');//Gets the ID value of the element
document.getElementById (' box '). id//gets the ID value of the element

document.getElementById (' box '). getattribute (' mydiv ');//Gets the custom attribute of the element
document.getElementById (' box '). mydiv;//Gets the custom attribute value of the element, non IE does not support

document.getElementById (' box '). getattribute (' class ');//Gets the class value of the element, non IE does not support
document.getElementById (' box '). getattribute (' className ');//non IE not supported


Ps:html Common Properties style and Onclick,ie7 lower version style returns an object, and the onclick returns a functional formula. Although IE8 has
Fixed this bug, but for better compatibility, the developer only avoids using getattribute to access HTML attributes as much as possible, or encounters
Special properties get special compatibility handling.

Get classname across browsers
if (document.getElementById (' box '). getattribute (' className ') = = null) {
Alert (document.getElementById (' box '). Attribute (' class '));
}else{
Alert (document.getElementById (' box '). Attribute (' className '));
}

5.setAttribute () method
The SetAttribute () method sets an element attribute and value in the element. It needs to accept two parameters: the property name and the property value. If the property itself already exists,
Then it will be overwritten.

document.getElementById (' box '). SetAttribute (' Align ', ' center ');//Set properties and values
document.getElementById (' box '). SetAttribute (' BBB ', ' CCC ');//Set custom properties and values

PS: In IE7 and earlier versions, setting the class and style properties using the SetAttribute () method is ineffective. Although IE8 solved the bug
, but it is still not recommended for use.


6.removeAttribute () method
Removeattribure () can remove HTML attributes.
document.getElementById (' box '). Removeattribure (' style ');//Remove the Style property


Ps:ie6 and earlier versions do not support the RemoveAttribute () method.


Third, DOM node


1.node Node Properties
Nodes can be divided into element nodes, attribute nodes, and text nodes, and these nodes have three very useful properties.
respectively: NodeName, NodeType and NodeValue.

Information Node Properties
Node Type Nodenamenodetypenodevalue
Element node element name 1null
Attribute Node property Name 2 property value
Text node #text3 text content (does not contain HTML)

document.getElementById (' box '). nodename;//gets the label name of the element node, and tagname equivalent
document.getElementById (' box '). NODETYPE;//1, the type value of the element node
document.getElementById (' box '). The nodevalue;//element node itself has no content
Node itself places the pointer on the element <div></div>, that is, there is no value in itself
If you want to output the text content contained within <div>xxx</div>, then the front innerHTML
Alert (document.getElementById (' box '). InnerHTML);//Gets the text content inside the element node
Node can only get things from the current node

PS: Text nodes are not equal to text content

2. Hierarchy Node Properties
The hierarchy of nodes can be divided into two types: parent node and child node, sibling node. When we get one of the element nodes, we can
Use the Hierarchy node property to get the nodes of the related hierarchy.
Hierarchy Node Properties
Property Description
ChildNodes gets all child nodes of the current element node
Fistchild Gets the first child node of the current element node
LastChild gets the last child node of the current element node
Ownerdocument gets the document root node of the node, which is equivalent
ParentNode Gets the parent node of the current node
Previoussibing gets the previous sibling node of the current node
Nextsibing gets the next sibling node of the current node
Attributes gets the collection of all attribute nodes for the current element node


1.childNodes Properties
The ChildNodes property can get all child nodes of an element node that contains the element child nodes and the text child nodes.
var box = document.getElementById (' box ');//Get an element node
alert (box.childNodes.length);//Get all child nodes of this element node
Alert (box.childnodes[0]);//Gets the first child node object


Window.onload=function () {
var box = document.getElementById (' box ');
alert (box.childnodes);//nodelist collection, returns a list of all child nodes of the current element node
alert (box.childNodes.length);//3 child node
3 Sub-nodes: Test div<em> tilt </em> End
The first child node is: Test Div, this node is called: text node
The second child node is:<em> inclined </em>: This node is called the element node
The third child node is: End, this is a text node
Alert (box.childnodes[0]);//object text represents a literal node object
alert (box.childnodes[0].nodename);//#text, the text node does not have a label signature
alert (box.childnodes[0].nodetype);//3, the property value of the current node is a text node
alert (box.childnodes[0].nodevalue);//Get text content of a text node
alert (box.childnodes[0].innerhtml);//undefined invalid.
}

PS: When using childnodes[0] to return a child node object, it is possible to return an element child node. such as HtmlElement, it is possible
Returns the text child node, such as text. Element subnodes can use NodeName or tagname to get the label name, while the text child node
can be obtained using NodeValue.

for (var i = 0; i<box.childnodes.length;i++) {
The judgment is the element node, the output element is signed
if (Box.childnodes[i],.nodetype ===1) {
Alert (' element node: ' +box.childnodes[i].nodename);
The judgment is the text node, the output text content
}else if (Box.childnodes[i].nodetype ===3) {
Alert (' Text node: ' +box.childnodes[i].nodevalue);
}
}

The specific code is as follows:
Window.onload=function () {
var box = document.getElementById (' box ');
for (var i = 0; i < box.childNodes.length; i++) {
if (box.childnodes[i].nodetype===1) {
Alert (' element node: ' +box.childnodes[i].nodename);
}else if (box.childnodes[i].nodetype===3) {
Alert (' element node: ' +box.childnodes[i].nodevalue);
}
}
}


PS: When acquiring a text node, it is not possible to use the innerHTML property to output text content, this non-standard attribute must be obtained in the
element node to output the text contained within it.
alert (box.innerhtml); the first difference between//innerhtml and NodeValue

The first difference between ps:innerhtml and NodeValue is to take the value. Then the second difference is the assignment, NodeValue will be included in the
The HTML in the text is escaped into a special string, thus achieving the effect of creating a simple text.
Box.childnodes[0].nodevalue = ' <strong>abc</strong> ';//result is:<strong>abc</strong>
box.innerhtml = ' <strong>abc</strong> ';//Result: ABC


2.firstChild and LastChild Properties
The firstchild is used to get the first child node of the current element node, which is equivalent to the Childnodes[0];lastchild user getting the current element node's last
A child node, equivalent to Childnodes[document.getelementbyid (' box '). Childnodes.length-1].

alert (box.fistChild.nodeName);//Gets the label name of the first child node, #text, the text node is not marked
alert (box.lastChild.nodeName);//Gets the label name of the last child node, #text, the text node is not marked
alert (box.firstChild.nodeType);//3, gets the property name of the first child node
alert (box.lastChild.nodeType);//3, gets the property name of the last child node
alert (box.fistChild.nodeValue);//Gets the text content of the first child node
alert (box.lastChild.nodeValue);//Gets the text content of the last child node


3.ownerDocument Properties
The Ownerdocument property returns the node's Document object root node. The returned object is equivalent to document.
Alert (box.ownerdocument = = = document);//true, root node


4.parentNode, PreviousSibling, nextsibling properties
The ParentNode property returns the parent node of the node, and the PreviousSibling property returns the previous sibling node of the node, NextSibling property
Is the next sibling node that returns the node.

alert (box.parentNode.nodeName);//Gets the label name of the parent node
alert (box.lastChild.previousSibing);//Gets the previous sibling node of the last child node
alert (box.firstChild.nextSibing);//Gets the next sibling node of the first child node

alert (box.lastChild.previousSibing.nodeName);//Gets the label name of the previous sibling node of the last child node


5.attributes Properties
The Attributes property returns a collection of attribute nodes for the node.

PS: The time to traverse is from the back forward
var box = document.getElementById (' box ');
alert (box.attributes);//namenodemap
alert (box.attributes.length);//Returns the number of attribute nodes
Alert (box.attributes[0]);//attr, returns the last attribute node
alert (box.attributes[0].nodetype);//2, return node type
alert (box.attributes[0].nodevalue);//property value
Alert (box.attributes[' id ');//attr, returns the node with the ID of the property
Alert (Box.attributes.getNamedItem (' id '));//attr

6. Ignore blank text nodes
var BODY = document.getelementsbytagname (' body ') [0];//gets the BODY element node
alert (body.childNodes.length);//Get the number of child nodes, IE3, non-IE7


PS: In non-IE, the standard DOM has the ability to recognize the white space child nodes, so in Firefox browser is 7, and IE automatically ignored, if you want to
To maintain a consistent child element node, you need to manually ignore it.

var box = document.getElementById (' box ');

Filterspacenode (Box.childnodes);

function Filterspacenode (nodes) {
var ret = [];
for (var i = 0; i < nodes.length; i++) {
If you recognize a blank text node, do not add an array
if (Nodes[i].nodetype = = 3 &&/^\s+$/.test (nodes[i].nodevalue)) continue;
Add each element node to the array.
Ret.push (Nodes[i]);
}
return ret;
}

PS: The above method, using the method of ignoring the blank text node, adds the resulting element node to the array to return. There is also a way to
Delete the blank as a file node directly.

function Filterspacenode (nodes) {
for (var i = 0; i < nodes.length; i++) {
if (Nodes[i].nodetype = = 3&&/^\s+$/.test (nodes[i].nodetype)) {
After you get the blank node, move to the parent node and delete the child nodes
Nodes[i].parentnode.removechild (Nodes[i]);
}
}
return nodes;
}

PS: If FirstChild, LastChild, PreviousSibling, and nextsibling encounter white space nodes in the process of acquiring a node, how do we
Get rid of it?

function Removewhitenode (nodes) {
for (var i = 0; i<nodes.childnodes.length; i++) {
if (Nodes.childnodes[i].nodetype ===3 &&/^\s+$/.text (nodes.childnodes[i].nodevalue)) {
Nodes.childnode[i].parentnode.removechild (Nodes.childnodes[i]);
}
}
return nodes;
}


Iv. node operation
Dom can not only find nodes, but also create nodes, copy nodes, insert nodes, delete nodes, and replace nodes.

Node Operation method

Method description
Write () This method can insert any string into the document
CreateElement () Create an element node
AppendChild () Appends a new node to the end of the list of child nodes
createTextNode () Create a file node
InsertBefore () Inserts a new node in the front
Repalcechild () Replace the new node with the old node
CloneNode () Copy node
RemoveChild () removing nodes


1.write () method
The write () method can insert any string into the document.
document.write (' <p> This is a paragraph </p> ');//output arbitrary string

2.createElement () method
The createelement () method can create an element node.
Document.createelement (' P ');//Create an element node

3.appendChild () method
The AppendChild () method tells you that a new node is added to the end of the list of child nodes of a node.
var box = document.getElementById (' box ');//Get an element node
var p = document.createelement (' P ');//Create a new element node <p>, just create a new element node, not yet added to the document, just reside in memory
Box.appendchild (P);//Put new element node <p> add end of child node

4.createTextNode () method
The createTextNode () method creates a text node.
var text = document.createTextNode (' paragraph ');//Create a text node
P.appendchild (text);//Add a text node to the end of a child node

Document.getelementsbyname (' body ') [0].appendchild (' Test div ');

5.insertBefore () method
The InsertBefore () method allows you to create a node before the specified node.
Box.parentnode is the body.
Box.parentNode.insertBefore (P,box);//create a node before <div>
Add a P to the box's parent node to add an element node in front of the box

The Ps:insertbefore () method creates a node in front of the current element, but does not provide a node behind the current element.
Well, we can create a InsertAfter () function with our own knowledge.

var box = document.getElementById (' box ');
var p = document.createelement (' P ');
InsertAfter (P,box);

function InsertAfter (newelement,targetelement) {
Get parent Node
var parent = Targetelement.parentnode;
If the last child node is the current element, add it directly
if (parent.lastchild = = = Targetelement) {
Parent.appendchild (newelement);
}else{
Otherwise, before the next node of the current node is added
Parent.insertbefore (newElement.targetElement.nextSibing);
}
}

Ps:createelement when creating a generic element node, browser compatibility is better. But on several special labels, such as the IFRAME
, input in the Radio and checkbox, Button element, may be in the browser below ie6,7 some incompatible.

var input = null;
if (Browserdelect.browser = = ' Internet Explorer ' && browserdelect.version <=7) {
Judge ie6,7, the way you use strings
input = document.createelement ("<input type = \" radio\ "name = \" Sex\ ">");
}else{
Standard browser, using standard mode
input = document.createelement (' input ');
Input.setattribute (' type ', ' Radio ');
Input.setattribute (' name ', ' sex ');
}
document.getElementsByTagName (' body ') [0].appendchild (input);

6.repalceChild () method
The Repalcechild () method can replace a node with a specified node.
Box.parentNode.repalceChild (P,box);//convert <div> to <p>

7.cloneNode () method
The CloneNode () method can be copied out of the node.
var box = document.getElementById (' box ');
var clone = Box.firstChild.cloneNode (TRUE);//Get first child node, true means copy content
Box.appendchild (clone);//Add to child node
Cloning a node, if true, is to clone the text in the tag, and if it is false, only the tag is cloned.

var box = document.getElementById (' box ');
var clone = Removewhitenode (box). Firstchild.clonenode (true);//Get first child node, true means copy content
Box.appendchild (clone);//Add to child node

Remove a blank node
function Removewhitenode (nodes) {
for (var i = 0; i<nodes.childnodes.length; i++) {
if (Nodes.childnodes[i].nodetype ===3 &&/^\s+$/.text (nodes.childnodes[i].nodevalue)) {
Nodes.childnode[i].parentnode.removechild (Nodes.childnodes[i]);
}
}
return nodes;
}


8.removeChild () method
The RemoveChild () method can
Box.parentNode.removeChild (box);//delete the specified node

17.DOM Foundation

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.