JavaScript DOM (i)

Source: Internet
Author: User
Tags pear shallow copy unique id

Directory:

    • Dom Family tree
    • Basic properties and methods of a node
    • Document and GetElement method
Dom Family tree

The DOM can portray any HTML or XML document as a structure composed of multi-level nodes. The nodes are divided into several different types, each representing different information or tags in the document. Each node has its own properties and methods, and there is a relationship with the other nodes.

The DOM describes a document's hierarchy as a "tree" model, or, more specifically, a family tree. It uses titles such as parent,child,sibling to indicate the relationship between family members.

In order to understand the hierarchical structure described by DOM we might as well cite:

<! DOCTYPE html><html>  <head>    <meta charset="gb2312" />    <title>Fruit</title>  </head>  <body>    <h2>Nice Fruit</H2>    <p Title="A List of fruit">Eat them usually.</P>    <ul id="List1">      <li class="Fruit">Apple</li>      <li class="Fruit">Watermelon</li>      <li class="Fruit">Pear</li>      <li class="Fruit">Orange</li>    </ul>  </body></html>

The above document model can be represented by the following family tree:

Obviously, in this family tree, HTML is the root element.

The HTML has 2 child, the head and body respectively. Both of them are child nodes of the root element, and each other is a sibling node. HTML is their parent node.

Continuing down, we can see that the body has 3 child nodes. H2,p,ul, the three are sibling nodes, they have a common parent node body. At the same time, UL is also the parent node of 4 Li nodes.

The body's sibling node head has 2 sub-nodes: Meta and title.

Basic properties and methods of a node

In JavaScript, there are 12 types of nodes:

    • Node.element_node
    • Node.attribute_node
    • Node.text_node
    • Node.cdata_section_node
    • Node.entity_reference_node
    • Node.entity_node
    • Node.processing_instruction_node
    • Node.comment_node
    • Node.document_node
    • Node.document_type_node
    • Node.document_fragment_node
    • Node.notation_node

The above 12 types, respectively, correspond to the 1~12 numeric constants. Any node must belong to one of them. In fact, all types of nodes implement the node interface. In JavaScript, that is, the node type is inherited, so all nodes have common basic properties and methods.

Basic properties of a node
Basic methods of node operation

Basic properties of the node 1, NodeType, NodeName, and NodeValue properties

All node types belong to one of the above 12 types. The NodeType property in the node stores the type value of the node.

For example, html,body,p and other element types of nodes, their types belong to Node.element_node, corresponding to the value of 1.

NodeName and NodeValue contain more information about the nodes, depending on the specific node type. For example, for a node of element type (Node.element_node), NodeName represents the label name of the element (for example: body,ul,p), NodeValue is null, and for document type (Node.document_node), NodeName is "#document" and NodeValue is null.

2. ChildNodes Properties

The relationships between the nodes in the document are described by parent,child,sibling and so on. Each node has a ChildNodes property that holds a NodeList object.

NodeList is an array-like object designed to hold a set of ordered nodes that we can access in the following ways:

方括号:someNode.childNodes[i]item():someNode.childNodes.item(i)

The NodeList object is a length property that represents the number of nodes that are saved:

someNode.childNodes.length

It should be emphasized that the NodeList object is the result of a dynamic query based on the DOM structure, so that the object changes when the DOM structure changes. So the following code produces a dead loop:

vardocument.getElementsByTagName("div"), i, div;for0; i < divs.length; i ++) {    document.createElement("div");    document.body.appendChild(div);}
3. ParentNode Properties

Each node has a ParentNode property that points to the parent node of the node. If the node does not have a parent node, this value is null.

4, FirstChild and LastChild properties

As the name implies, for a parent node, these two properties point to the first child node and the last child node, respectively. If the node has no child nodes, both values are null. If there is only one child node, the two values are equal.

5, PreviousSibling and NextSibling properties

The parent node's ChildNodes property points to a NodeList object, which holds a set of ordered nodes. These nodes are sibling nodes, and they can be accessed through the PreviousSibling and NextSibling properties.

The PreviousSibling property points to the previous node of this node, and if the node itself is the first node, this value is null. Similar to the NextSibling property, it points to the next adjacent node of this node, and if the node is the last node, this value is null.

6, Ownerdocument

This property is also common to all nodes, pointing to the document node that represents the entire document. This property also indicates that any node must belong to the document it is in, and that it is the only one that belongs to the document. This attribute gives us the convenience of backtracking, and we can jump directly to the top of the document without having to backtrack in the middle layer of the structure layer.

For the above several attributes that represent the relationship of the nodes, we can represent them in slices:

Basic methods of node operation 1, AppendChild ()

This method is used to add a node to the end of the ChildNodes list and return the node.

Note that the DOM structure is updated dynamically each time the addition is completed.

var node1 = someNode.appendChild(newNode);alert(node1 == newNode);  //truealert(someNode.lastChild == node1)  //true
2, InsertBefore ()

This method inserts the node in front of the specified node. The method receives 2 parameters: the node to be inserted, the reference node. For example:

    var node = someNode.insertBefore(newNode, someNode.firstChild);  //插入到第一个节点之前    var node = someNode.insertBefore(newNode, someNode.lastChild);  //插入到最后一个节点之前    varlen = someNode.childNodes.length;    var node = someNode.insertBefore(newNode, someNode.childNodes[len - 2]);  //插入到倒数第二个节点之前
3, ReplaceChild ()

This method is used to replace a child node. The method also receives 2 parameters: the node to be inserted, the node to be replaced. For example:

    varlen = someNode.childNodes.length;    var node = someNode.replaceChild(newNode, someNode.childNodes[len - 4]);  //替换倒数第四个节点
4, RemoveChild ()

This method is used to remove a child node from the DOM structure, which accepts only one parameter: the node that needs to be moved out. It is important to note that the nodes that are moved out of the method will still exist in the document, but no longer exist in the document hierarchy.

5, CloneNode ()

The method exists in all nodes and accepts a Boolean parameter. Used to clone this node. Clones are divided into 2 types: deep copy, shallow copy.

Deep copy Returns the result of this node and all child node trees contained in this node. Shallow copy returns only one copy of the current node. Whether a deep copy or a shallow copy, the copy returned after the copy is the same as the node that was moved by the RemoveChild () method, exists in the document, but does not have its location in the DOM tree. We can add it to the node tree by using the node action method above.

    var nodeTree = someNode.cloneNode(true);  //参数为true时表示深复制    var node = someNode.cloneNode(false);  //参数为false时表示浅复制 
6, HasChildNodes ()

The method detects whether the node contains child nodes, returns True when included, or False if it is returned. Because of the dynamic nature of nodelist, when we access the length property of ChildNodes, we execute a query of all its elements, in this sense, using the HasChildNodes () method to confirm whether a node contains child nodes is a simpler method.

Document and GetElement method

In JavaScript, the Document object represents the entire HTML page and is also a property of the Window object, so we can access it through the global object.

The most common thing about a Document object is that it uses the GetElement method to get an element reference.

Let's take the example of the code that begins with the family tree:

<! DOCTYPE html><html>  <head>    <meta charset="gb2312" />    <title>Fruit</title>  </head>  <body>    <h2>Nice Fruit</H2>    <p Title="A List of fruit">Eat them usually.</P>    <ul id="List1">      <li class="Fruit" name="Li1">Apple</li>      <li class="Fruit" name="Li2">Watermelon</li>      <li class="Fruit" name="Li3">Pear</li>      <li class="Fruit" name="Li4">Orange</li>    </ul>  </body></html>
    • Getelemetbyid
    • getElementsByTagName
    • Getelementsbyname
    • Getelementsbyclassname
Getelemetbyid

This method allows us to get a reference to the element by its ID. The method accepts a parameter: to get the ID value of an element, NULL is returned if no element of that ID exists. For example, to obtain a reference to the UL element in the code above, you can use the following method:

var ulList = document.getElementById("list1");

Each element in the document is a reference to an object type, so we get an object when we use TypeOf to detect the above code:

alert(typeof ulList);  //object
getElementsByTagName

Many times we do not define a unique ID for each element in the document, and we can use the getElementsByTagName () method in order to get a reference to the element. The method receives a parameter: the label name of the element to get. The method returns a collection of elements that contain the specified label name.

Such as:

var myLi = document.getElementsByTagName("li");

This way we get a reference to all of the LI elements. In HTML, the reference is a reference to a Htmlcollection object, which, like NodeList, accesses the elements in square brackets [] and item (), and also has the length property itself.

alert(myLi.length);  //4alert(myLi[1].name);  //li2alert(mtLi.item(0).name);  //li1

At the same time, the Htmlcollection object has a Nameditem () method that allows us to more easily access the elements in the element name:

myLi.namedItem("li2")

When we use the wildcard character "*" as an argument, we will get a reference to all elements of the entire page, in Htmlcollection, which are arranged in the order in which they appear. For example, get a reference to all the elements of the above page:

var all = document.getElementsByTagName("*");alert(all.length);  //12alert(all[0]);  //htmlalert(all[1]);  //headalert(all[2]);  //meta
Getelementsbyname

The method returns all elements with the given name attribute, which takes a parameter to get the name of the element.

The use of the element to get the specified name is simple:

var fruit1 = document.getElementsByName("li0");

Here, let's take another very common example--to get a radio button:

<ul>  <li><input type="Radio" value="Red" name="Color"  id="Red"><label for ="Red">Red<lable></li>  <li><input type="Radio" value="White" name="Color"  id="White"><label for =' white '>White<lable></li>  <li><input type="Radio" value="Black" name="Color"  id="Black"><label for ="Black">Black<lable></li></UI><script> var radios = document.getelemtnbyname ("Color");  </script>

The above code obtains the Htmlcollection object for all radio buttons. It is important to note that because the name of all elements in the radios is color, we only get the first item through the Nameditem ("Color") method.

Getelementsbyclassname

The Getelementsbyclassname () method is added to the HTML5 DOM, which takes a parameter, which is the class name of the element to get. The method obtains a collection of elements that contain the specified class name. Such as:

var myFruit = document.getElementsByClassName("fruit");

For some browsers that do not provide support for this method, we can also easily give cross-browser solutions by traversing the method:

 function getelementbyclass(node, className) {    if(Node.getelementsbyclassname) {returnNode.getelementsbyclassname (ClassName); }Else{varRETs =New Array();varEles = Node.getelementbytagname ("*"); for(vari =0; i < eles.length; i + +) {if(Eles[i].calssname.indexof (className)! =-1) {Rets[rets.length] = eles[i];} }returnRETs }}

JavaScript DOM (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.