JavaScript Dom Basics _ Basics

Source: Internet
Author: User
Tags tagname

The DOM (Document Object model), which is an API for HTML and XML documents (the application interface);

The DOM depicts a hierarchical node tree in which developers can add/remove and modify portions of the page;

Introduction to a DOM

D (document): Can be understood as the entire Web page loaded documents;
O (object): Can be understood as something like a Window object, you can invoke properties and methods, here is the document object;
M (model): Can be understood as a Web page document tree structure;

1. Node

When the HTML page is loaded, the Web browser generates a tree structure that represents the internal structure of the page;
This node structure is understood by Dom as composed of nodes;
The HTML element is the root node; the head element is the child node of the HTML; the meta element and the title element are brothers;


2. Node type: element node/text node/attribute node
<div title= "element Properties" > Test div</div>
element node => Div;
Attribute node => title= "Element Properties"
Text node => Test div Two Find element
The consortium provides a convenient and simple method and attribute for locating nodes so that we can operate the nodes quickly.
The DOM (Document Object model), which is an API for HTML and XML documents (the application interface);

The DOM depicts a hierarchical node tree in which developers can add/remove and modify portions of the page;

Element Node Lookup method
Method Description
getElementById () Gets the node of the specific ID element;
getElementsByTagName () Gets the list of nodes for the same element;
Getelementsbyname () Gets a list of nodes with the same name;
GetAttribute () Gets the value of a specific element node property;
SetAttribute () Sets the value of a specific element node property;
RemoveAttribute () removes a specific element node attribute;

1.getElementById ()

Method receives an argument: Gets the ID of the element;
Returns the Htmldivelement object of the element if the element is found, or null if it does not exist;
document.getElementById (' box '); [Object Htmldivelement];
When we get to a particular element node through getElementById (), the node object is captured by us;
And through this node object, we can access its series of attributes;
(1). Accessing the attributes of an element node
Attribute description
TagName gets the label name of the element node;
InnerHTML gets the content in the element node, not the DOM specification;
document.getElementById (' box '). TagName; =>div;
document.getElementById (' box '). InnerHTML; => Test Div;

(2). Access HTML Common Properties
    properties                               Instructions
    id                The ID name of the             element node;
    title              The title attribute value of the            element node;
    style                         CSS inline style attribute value;
    classname                     a class of CSS elements;

document.getElementById (' box '). ID; =>id;
document.getElementById (' box '). title; Get title;

document.getElementById (' box '). style; Get the Cssstyledeclaration object;
document.getElementById (' box '). Style.color; Gets the value of the color in the style object, which is the style value set in the element row;
document.getElementById (' box '). style.color= ' Red '; Sets the value of a color in a style object;

document.getElementById (' box '). ClassName; Get class;
document.getElementById (' box '). Classname= ' pox '; Set class;

document.getElementById (' box '). BBB; Gets the value of the custom attribute, not supported by IE;


2.getElementsByTagName ()
//method returns an array of object arrays Htmlcollection (nodelist), which holds a list of nodes with all the same element names;
document.getElementsByTagName (' * '); Using wildcard characters to get all the elements;
When using wildcard characters, ps:ie the first element node of the document's initial HTML specification declaration;

document.getElementsByTagName (' Li '); =>[object Htmlcollection]; get all LI elements;
document.getElementsByTagName (' Li ').    [0]; Gets the first LI element;

3.getElementsByName ()

Gets the element that has the same name setting, and returns an array of objects htmlcollection (nodelist);
Document.getelementsbyname (' Add '); Gets a collection of input elements with name= ' add ';
PS: For not HTML legitimate attributes, then the compatibility of JS Access will also be different;
IE supports the legitimate Name property, but there is an incompatibility problem with custom attributes;

4.getAttribute ()
method Gets the value of an attribute in the element;
But there is a certain difference between it and the direct use of ". attr" to get property values;
document.getElementById (' box '). getattribute (' mydiv '); Gets the custom property value;
document.getElementById (' box '). Mydiv; Gets the custom attribute value, IE support only;

5.setAttribute ()
method sets an attribute and value in the element, receives two parameters: the property name and the value;
If the property itself already exists, it is overwritten;
document.getElementById (' box '). setattribute (' Align ', ' center '); Set properties and values;
PS: In IE7 and below, using the SetAttribute () method to set the class and style properties has no effect;

6.removeAttribute ()
method to remove HTML attributes;
document.getElementById (' box '). RemoveAttribute (' style '); Removes the style style property;

Three DOM nodes

1.node Node Properties

Nodes can be divided into: element node/attribute node and text node;
These nodes all have three attributes: Nodename/nodetype and NodeValue;

Information Node Properties
Node type nodename nodeType nodevalue
element element name 1 null
Property Property Name 2 property value
Text #text 3 Text content
document.getElementById (' box '). NodeType; =>1; element node;

2. Hierarchical Node Properties
Hierarchical nodes can be divided into: parent node and child node/sibling node;

When we get one of the element nodes, we can use the hierarchical node attribute to get the node of the related level.

Diagram of node relationship

Hierarchical Node Properties
    Properties                           Description
childnodes              reads all child nodes of the current element node; The
firstchild             reads the first child node of the current element node; The
lastchild              gets the last child node of the current element node; The
ownerdocument          gets the document root node of the node, which is equivalent to documents; The
parentnode             gets the parent node of the current node;
previoussibling        Gets the previous sibling node of the current node;
nextsibling            Gets the latter sibling node of the current node;
attributes             gets a collection of all the attribute nodes of the current element node;

(1). ChildNodes Property

Property gets all the child nodes of an element node that contain element nodes and text nodes;
PS: When using Childnodes[n] to return a child node object, it is possible to return the element child nodes, such as: HtmlElement;
It is also possible to return a text child node, such as: text;
Element child nodes can obtain the label name using NodeName or tagname, while the text child nodes can be obtained using NodeValue;
var box = document.getElementById (' box ');
for (var i=0; i<box.childnodes.length; i++) {
The judgment is the element node, the output element label name;
if (Box.childnodes[i].nodetype = = 1) {
Console.log (' element node: ' +box.childnodes[i].nodename ');
The judgment is the text node, the output text content;
}else if (Box.childnodes[i].nodetype ===3) {
Console.log (' text node: ' +box.childnodes[i].nodevalue ');
}
}
PS1: When acquiring a text node (the emphasis is already not an element node), it is not possible to use the innerHTML attribute to output text content;
This non-standard attribute must be acquired in order to output the text contained in the element node.
alert (box.innerhtml); The first difference between innerHTML and nodevalue;

Ps2:innerhtml and NodeValue in the assignment, NodeValue will be included in the text of the HTML to escape into special characters, so as to achieve the effect of the formation of pure text;
And innerHTML will parse the special characters in the text;
Box.childnodes[0].nodevalue = ' <strong>abc</strong> '; =><strong>abc</strong>;
box.innerhtml = ' <strong>abc</strong> '; =>ABC (style bold);

(2). FirstChild and LastChild Properties
FirstChild = Childnodes[0]; Gets the first child node of the current element;
LastChild = Childnodes[box.childnodes.length-1]; Gets the last child node of the current element;

(3). Ownerdocument Property
Returns the Document object root node of the node, and the object returned is the equivalent of document;
Alert (box.ownerdocument = = document); =>true; root node;

(4). Parentnode/previoussibling/nextsibling Property

ParentNode: Returns the parent node of the node;
PreviousSibling: Returns the previous sibling node of the node;
NextSibling: Returns the latter sibling node of the node;
alert (box.parentNode.nodeName); Gets the label name of the parent node;
alert (box.firstChild.nextSibling); Gets a second node;
alert (box.lastChild.previousSibling); Gets the penultimate node;

(5). Attributes property
property returns a collection of property nodes for that node;
Alert (document.getElementById (' box '). attributes); =>namednodemap;

(6). Ignore Blank text node

  var BODY = document.getelementsbytagname (' body ') [0];//gets the BODY element node;           alert (body.childNodes.length);  Non-ie=7;

  ie=3;
  PS: In non ie, the standard DOM has the function of recognizing the blank text node, while IE automatically ignores it;
    function FilterSpaceNode1 (nodes) {//new array;
    var ret = [];
      for (var i=0; i<nodes.length; i++) {//If a blank text node is recognized, it is not added to the 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 file node, adds the resulting element nodes to the array to return; function FilterSpaceNode2 (nodes) {for (var i=0; i<nodes.length; i++) {if (Nodes[i].nodetype ===3 &&/^\
        S+$/.test (Nodes[i].nodevalue)) {///After a blank node is removed, a child node is deleted on a parent node;
      Nodes[i].parentnode.removechild (Nodes[i]);
  } return nodes;
  The method of processing the blank node when acquiring the node is ps:firstchild. function Removewhilenode (nodes) {for (var i=0; i<nodes.childnodes.length; i++) {if (Nodes.childnodes[i].nodetyp E ===3 &&/^\s+$/.test (Nodes.childnodes[i].nodevalue)) {nodes.childnodes[i].parentnode.removechild (nodes.childnodes[i]);
  } return nodes; }

Four node operation
//DOM can not only find nodes, it can also create nodes/replication nodes/INSERT nodes/delete nodes and replace nodes

Node Action method
Method description
Write () This method can insert any string into the document;
CreateElement () creates an element node;
AppendChild () Appends the new node to the end of the child node list;
createTextNode () creates a file node;
InsertBefore () Inserts the new node in front;
ReplaceChild () replaces the old node with the new node;
CloneNode () copy node;
RemoveChild () remove node;

(1). Write () method
//write () method to insert any string into the document;
document.write (' <p> This is a paragraph!</p> '); After parsing the text;

(2). createelement () method
the CreateElement () method can create an element node;
Document.createelement (' P '); [Object Htmlparagraphelement];

(3). AppendChild () method
the AppendChild () method adds a new node to the end of the list of child nodes of a node;
var box = document.getElementById (' box ');
var p = document.createelement (' P '); Create a new element node <p>;
Box.appendchild (P); Add the new element node <p> the end of the child node;

(4). createTextNode () method
This method creates a text node;
var text = document.createTextNode (' paragraph ');
P.appendchild (text); Adds a text node to the end of a child node;

(5). InsertBefore () method

This method can add nodes to the front of the specified node;
  Box.parentNode.insertBefore (P,box);      Add a <p>;
  before <div> Box.insertbefore (newnode,null);        Add NewNode to the last node of the box from the list;

  The Ps:insertbefore () method creates a node before the current element, but does not provide the following to create a node behind the current element;
  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, add before the next node of the current node, and achieve the need
      to add nodes after the current node; Parentnode.insertbefore (newelement,targetelement.nextsibling);
    }
  

(6). ReplaceChild () method
the method can replace the node with the specified node;
Box.parentNode.replaceChild (P,box); Replace <div> with <p>;

(7). CloneNode () method

The method can be copied from the handle node, and the copy of the node returned after the copy belongs to the document, but does not specify a parent node for it;
Parameter is true: Deep replication is performed, which is the replication node and its entire child node tree;
Parameter is false: Shallow replication is performed and only the node itself is replicated;
var box = document.getElementById (' box ');
var clone = Box.firstChild.cloneNode (true); Gets the first child node, true indicates that the content is replicated;
Box.appendchild (clone); Add to the end of the child node list;

(8). RemoveChild () method
The method deletes the specified node;
Box.parentNode.removeChild (box);

Summary: In the next chapter ~

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.