Hierarchical node of Dom in JavaScript (i)

Source: Internet
Author: User
Tags shallow copy

Dom is an API for HTML and XML documents that depicts a hierarchical node tree that allows developers to add, modify, and delete part of a node.

The DOM depicts HTML and XML documents as a structure with multiple nodes divided into 12 different node types, each with its own characteristics, data, and methods, and a relationship with other nodes.

HTML elements are called document elements, and all elements are contained in document elements, and each document has only one HTML element.

1 node type

The DOM1 class defines the node interface, which is implemented by all node types in the DOM. This interface is implemented as a node type in JavaScript. So all node types in JavaScript inherit the nodes type, and all types share the same basic properties and methods.

    1. Node.element_node (1)
    2. Node.attribute_node (2)
    3. Node.text_node (3)
    4. Node.cdata_section_node (4)
    5. Node.entity_reference_node (5)
    6. Node.entity_node (6)
    7. Node.processing_instruction_node (7)
    8. Node.comment_node (8)
    9. Node.document_node (9)
    10. Node.document_type_node (10)
    11. Node.document_fragment_node (11)
    12. Node.notation_node (12)

Because IE has no public constructors, the above code cannot be used in IE. So to ensure cross-browser compatibility, the method for determining the node type is as follows:

    if(someNode.nodeType == 1){ alert("this is a element node!"); }
1.1 NodeName and NodeValue

You can use the NodeName and NodeValue properties to understand node's specific information, which is related to the type of node.

    if(someNode.nodeType == 1){ value = someNode.nodeName; //对于元素节点,nodeName保存的是元素的标签名,nodeValue始终为null }
1.2 Node relationship

All nodes in the document are related to each other, including parent-child relationships, and sibling relationships.

Each node has a ChildNodes property, holds a NodeList object, NodeList is an object of an array of classes that can be accessed using Childenode[0],childnode.item (1), with the length property, But not an array instance.

    • ParentNode: Parent node pointing to the document tree
    • NextSibling: Next node adjacent to the current node
    • PreviousSibling: Next to the previous node of the current node
    • FirstChild: Shows the first node of a node, childnodes[0]
    • LastChild: Represents the last child node of a node, childenodes[childnodes.length-1]
1.3 Node operation
    • HasChildNodes () Method: Determines whether a node has child nodes, has a return of true, does not return false
    • RemoveChild () Method: To remove a node
    • AppendChild () Method: Add a node, delete it if it already exists in the document tree, and insert it in the new location
    • ReplaceChild (Node1,node2) method: Removes the specified node node2 from the document tree, inserts the node Node1, the node being replaced is still in the document, but no location
    • InsertBefore (Node1,node2) method: Inserts the node Node1 in front of the specified node Node2 and returns NODE1. If it already exists, delete the original and insert it in the new location
    • CloneNode () Method: Copies a node that has one parameter, true for deep copy, and false for shallow copy. Properties, handlers, and so on are not copied.
2 doucument Type

The Document object is an instance of HTMLDocument (inherited from document type) that represents an entire HTML page or other XML-based document. and document is a property of the Window object that can be accessed as a global object.

type value
NodeType 9
NodeName #document
NodeValue Null
ParentNode Null
2.1 Text Node

The child nodes of document can be DocumentType, Element, Processinginstructior, or comment, with two shortcuts to access nodes:

    • documentElement, the property always points to the HTML element in the page.
    • childNodesTo access the document element directly.
    • document.body, pointing directly to the BODY element
    • doucment.doctype, get the information of the label

The document type is read-only, and it has only one element node, which is usually already present.

2.2 Document Information

The Document object has properties that the standard document object does not have, and provides some information about the Web page that the document object is performing.

        Get document titlevar title=Document.Title;Set the document titleDocument.Title="New page title";Get the full URLvar URL=Document.Url;Get Domain Namevar domain=Document.Domain;Get the URL of the source pagevar referrer=Document.Referrer;Document.BgColorSet the page background colorDocument.FgcolorSet foreground colors (text color)Document.LinkColorNon-clicked link colorDocument.AlinkcolorColor of the activation link (focus on this link)Document.VlinkcolorThe color of the link that has been clickedDocument.FilecreateddateFile build date, read-only propertyDocument.FilemodifieddateFile modification date, read-only propertyDocument.FileSizeFile size, read-only propertyDocument.CookiesSet up and read out cookiesDocument.CharSetSet character sets Simplified Chinese: gb2312Document.BodySpecifies that the beginning and end of a document body is equivalent to body>/body>Document.Body.BgColorSets or gets the background color behind the objectDocument.Body.LinkNon-clicked link colorDocument.Body.ALinkColor of the activation link (focus on this link)Document.Body.VlinkThe color of the link that has been clickedDocument.Body.TextText colorDocument.Body.InnerTextSet the text between body>.../body>Document.Body.InnerHTMLSet the HTML code between body>.../body>document. Body. topmargin //page top margin document. body. leftmargin //page left margin document. body. rightmargin //page right margin document. body. bottommargin //page bottom margin document. body. background //background image        
2.3 Finding elements

The document type provides two ways to find elements:

    1. getElementById()Returns the element if the corresponding element is found, or null if no element with the corresponding ID exists.
    2. getElementByTagName(), returns a nodelist containing 0 or more elements, and in an HTML document, this method returns a Htmlcollection object, very similar to nodelist. Where the Thmlcollection object has a method Nameditem ()
    3. getElementsByName(), all elements with the given name attribute are returned.
        var images=Document.getElementsByTagName ("IMG");AlertImages.Length//the number of output images alert (Images[0]. SRC) ;//outputs the SRC attribute of the first image element alert (images. Item (0).  SRC) ;//output the SRC attribute of the first image element //get individual photos by name var myimage = images. Nameditem ( "myimage") = Images[;        
2.4 Document Writing

The document.write () method can be used in two ways:

    1. Create page content with real-time scripting during page loading
    2. Create the contents of this window or new window with a delay script

The document.write () function is only executed when the page is loaded

Doucment.writeln () is similar to the above, except that the line is wrapped.
Open () and close () are used to turn on and off the output stream of the Web page, and if write () is used during page load, both methods are not required.

3 element type

The element type is used to represent XML or HTML elements, providing access to element tag names, child nodes, and attributes.

type value
NodeType 1
NodeName Signature of the element
NodeValue Null
ParentNode Documnet or element
3.1 HTML elements

All HTML elements are represented by the HtmlElement type, and the HtmlElement type inherits directly from element and adds some properties. The attributes that are added correspond to the following standard attributes that exist in each HTML element.

    var div =  document. getelementbyid ( "mydiv") //can get and set the value of the property alert (div. id) alert (div.classname) alert (div.title) alert (div.lang) alert (div.dir) //gets the text direction of the element           
3.2 Operating Characteristics

GetAttribute (): Additional information used to obtain the corresponding element or its contents, which is basically the same as the obtained attribute above, but with two points of difference:

    1. The style, obtained through the getattribute (), is the CSS text that is obtained by the property and returns an object.
    2. Onclick,getattribute () Gets the string for the corresponding code, and the property fetch returns a JavaScript function.

In general, it is best for developers to use the properties of the object, as long as the custom eigenvalue is obtained, and the GetAttribute () is used.

SetAttribute (): Receives two parameters, the attribute name and value to be set, if the attribute already exists, modifies the attribute value and is created if it does not exist.

RemoveAttribute (): The attribute used to completely remove elements, IE6 and previous versions do not support this method.

3.3 Creating elements

The Document.createelement () method creates a new element that receives only one parameter, that is, the label name of the element to be created (not size-sensitive).

 /*** div Create insert process ***/var div = document. createelement ( "div") div.id =  "MyNewDiv "; div.classname =  " Box "; document. Body. appendchild (Div) ;            

Hierarchical nodes of the DOM in JavaScript (i)

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.