JavaScript DOM (i)

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

Folder:

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

The DOM is able to portray any HTML or XML document as a structure composed of multiple hierarchical nodes. The nodes are divided into several different types. Each type represents a different information or tag in the document. Each node has its own properties and methods, and there is a relationship with other nodes at the same time.

Dom describes the hierarchical structure of a document description as a "tree" model, or, more precisely, 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 of the DOM descriptive narrative, we'd better give an example:

<! 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.

HTML has 2 child, each of which is head and body. Both of them are child nodes of the root element. At the same time, they are all brothers nodes. HTML is their parent node.

Continuing down, we can see that the body has 3 child nodes. The H2 are respectively. P. UL, these 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. corresponding 1~12 numeric constants respectively. No matter what node it is, one of them must be among 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 of the 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. The corresponding number is 1.

NodeName and nodevalue include many other information about the nodes, depending on the detailed node type. For example, for a node of an element type (Node.element_node), NodeName represents the label name of the element (for example: body,ul,p), NodeValue is null. For document type (Node.document_node), NodeName is "#document". 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 a similar array of objects that are designed to hold an ordered set of nodes. We are able to access the nodes 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 saved in:

someNode.childNodes.length

It is emphasized that the NodeList object is the result of a dynamic query based on the DOM structure, so. When the DOM structure has changed. The object will change with it.

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.

Assuming that the node has no parent node, this value is null.

4, FirstChild and LastChild properties

Name implies. For a parent node. These two properties point to the first child node and the last child node, respectively. Assuming that the node has no child nodes, both values are null. Assuming that 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. They are able to access each other through the previoussibling and NextSibling attributes.

The PreviousSibling property points to the previous node of this node, assuming that the node itself is the first node. Then this value is null. The NextSibling property is similar, it points to the next adjacent node of this node, assuming that the node is the last node, then this value is null.

6, Ownerdocument

The same property is common to all nodes, pointing to the document node that represents the entire document. This property also represents the document in which the node must belong, regardless of its location. The same time also only belongs to the document. This property brings us back to the convenience of backtracking. We are able to 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 use the following image to represent:

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.

Notice every time. The DOM structure is updated dynamically when the addition is complete.

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, and the node to take the picture.

Like what:

    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 receives the same 2 parameters: the node to be inserted. The node that was replaced.

Like what:

    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 node that is called to move out of the method will still exist in the document, just that it does not exist in the document hierarchy.

5, CloneNode ()

The method exists in all nodes. 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 included in this node.

Shallow copy returns only one copy of the current node. Whether it's a deep copy or a shallow copy. The replica returned after replication is the same as the node that was moved out of 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 ()

This method checks to see if the node includes a child node, including when it returns True, otherwise returns false. Because of the dynamic nature of nodelist, when we visit the length property of ChildNodes, we run a query on all of its elements, in this sense. Using the HasChildNodes () method to confirm whether a node includes child nodes is a simpler approach.

Document and GetElement method

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

About the Document object. The most frequently used method is to obtain an element reference by means of the GetElement method.

Let's take the example of the code describing the genealogy tree at the beginning:

<! 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

The method agrees that we get a reference to the element by its ID. The method accepts a parameter: to get the ID value of an element, if there is no corresponding element for that ID. Returns NULL.

For example, we want to get a reference to the UL element in the above code. Be able to use the following methods:

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

Very often we do not define a unique ID for each element in the document, in order to obtain a reference to the element. We are also able to use the getElementsByTagName () method.

The method receives a parameter: the label name of the element to get. The method returns a collection of elements that include 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 that, like NodeList, can access the elements in square brackets [] and item (), and at the same time has its own length property.

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

At the same time, the Htmlcollection object, another Nameditem () method, allows us to access the elements more easily through the element name:

myLi.namedItem("li2")

When we use the wildcard "*" as a reference, we will get references to all elements of the entire page, and in Htmlcollection, they 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 example that is very often used 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 will only get the first of these through the Nameditem ("Color") method.

Getelementsbyclassname

The Getelementsbyclassname () method is added in the HTML5 DOM, which accepts a parameter, which is the class name of the element to get.

The method obtains a collection of elements that include 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 provide cross-browser resolution 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.