Home >Web Front-end >JS Tutorial >More detailed javascript DOM study notes_javascript skills

More detailed javascript DOM study notes_javascript skills

PHP中文网
PHP中文网Original
2016-05-16 19:03:40985browse

After reading a lot of js dom learning materials, I found this one is quite detailed, so I reprint it for everyone to learn about

1. DOM basics
1. Node level
Document--the most The top-level node to which all other nodes are attached.
DocumentType - the object representation of a DTD reference (using the 1a309583e26acea4f04ca31122d8c535 syntax), which cannot contain child nodes.
DocumentFragment - can save other nodes like Document.
Element - represents the content between the start tag and the end tag, such as 8bf259f5a6144433b921fb8b7de949700e9100648b0b4b6da2ed8dd45e1a0e54 or c5732311c9bc8f9578856d5c0fe1f791. This is the only node type that can contain both attributes and child nodes.
Attr - represents a pair of attribute names and attribute values. This node type cannot contain child nodes.
Text - represents the ordinary text between the start tag and the end tag in the XML document, or contained in the CDataSection. This node type cannot contain child nodes.
CDataSection - the object representation of 706a388e39e8555a9742f4594c5343bf. This node type can only contain text nodes Text as child nodes.
Entity - represents an entity definition in the DTD, such as f3953a0c47aa44cfd43076fe8e65b58d. This node type cannot contain child nodes.
EntityReference - represents an entity reference, such as ". This node type cannot contain child nodes.
ProcessingInstruction - represents a PI. This node type cannot contain child nodes.
Comment - represents XML comments. This node cannot contain child nodes.
Notation - represents the notation defined in the DTD. The

Node interface defines properties and methods that are included in all node types.


In addition to nodes, DOM also defines some helper objects, which can be used with nodes, but are not a necessary part of the DOM document.
NodeList - Node array, indexed according to value; used to represent the child nodes of an element.
NamedNodeMap - a node table indexed by both values ​​and names; used to represent element characteristics.

2. Access related nodes
Consider the following HTML page in the following sections

<html>
    <head>
        <title>DOM Example</title>
    </head>
    <body>
        <p>Hello World!</p>
        <p>Isn&#39;t this exciting?</p>
        <p>You&#39;re learning to use the DOM!</p>
    </body>
</html>

To access the ab9f710e8a95de8822eb06cf01adf4e6 element (you should understand that this is the document element of the document), you can use the documentElement attribute of document:
var oHtml = document.documentElement;
Now The variable oHtml contains an HTMLElement object representing ab9f710e8a95de8822eb06cf01adf4e6. If you want to get the 5d86db81e494b82c29e979209d098205 and b2636b4e0e32f7cd731b9073897693b7 elements, the following can be achieved:
var oHead = oHtml.firstChild;
var oBody = oHtml.lastChild;
can also be used childNodes attribute to accomplish the same job. Just treat it as a normal javascript array, marked with square brackets:
var oHead = oHtml.childNodes[0];
var oBody = oHtml.childNodes[1];
Note that the square brackets are actually Simple implementation of NodeList in javascript. In fact, the official way to get child nodes from the childNodes list is to use the item() method:
var oHead = oHtml.childNodes.item(0);
var oBody = oHtml.childNodes.item(1);
The HTML DOM page defines document.body as a pointer to the b2636b4e0e32f7cd731b9073897693b7 element.
var oBody = document.body;
With the three variables oHtml, oHead and oBody, you can try to determine the relationship between them:
alert(oHead.parentNode==oHtml);
alert(oBody.parentNode==oHtml);
alert(oBody.previousSibling==oHead);
alert(bHead.nextSibling==oBody);
alert(oHead.ownerDocument==document);
The above all outputs "true".

3. Processing attributes
As mentioned earlier, even though the Node interface already has the attributes method and has been inherited by all types of nodes, however, only the
Element node can have attributes. The attributes attribute of the Element node is actually NameNodeMap, which provides some methods for accessing and processing its content:
getNamedItem(name)--returns the node whose nodename attribute value is equal to name;
removeNamedItem(name)--delete A node whose nodename attribute value is equal to name;
setNamedItem(node)--add node to the list and index according to its nodeName attribute;
item(pos)--like NodeList, return the node at position pos ;
Note: Please remember that these methods return an Attr node, not an attribute value.

The NamedNodeMap object also has a length attribute to indicate the number of nodes it contains.
When NamedNodeMap is used to represent attributes, where each node is an Attr node, the nodeName attribute is set to the attribute name, and the nodeValue attribute is set to the attribute value. For example, suppose there is such an element:
f703f6ab3d857132f2daf9892a29a3a9Hello world!94b3e26ee717c64999d7867364b1b4a3
At the same time, suppose the variable oP contains a pointer to this element Quote. So you can access the value of the id attribute like this:
var sId = oP.attributes.getNamedItem("id").nodeValue;
Of course, you can also access the id attribute numerically, but this is a little unintuitive:
var sId = oP.attributes.item(1).nodeValue;
You can also change the id attribute by assigning a new value to the nodeValue attribute:
oP.attributes.getNamedItem("id").nodeValue=" newId";
Attr node also has a value attribute that is completely equivalent to (and completely synchronized with) the nodeValue attribute, and has a name attribute that is synchronized with the nodeName attribute. We are free to use these properties to modify or change properties.
Because this method is somewhat cumbersome, DOM defines three element methods to help access attributes:
getAttribute(name) - equal to attributes.getNamedItem(name).value;
setAttribute(name,newvalue) --Equal to attribute.getNamedItem(name).value=newvalue;
removeAttribute(name) --Equal to attribute.removeNamedItem(name).

4. Access the specified node
(1)getElementsByTagName()
Core (XML) DOM defines the getElementsByTagName() method to return a tagName() A NodeList of elements whose tag name) attribute is equal to a specified value. In an Element object, the tagName attribute is always equal to the name immediately following the less than sign -- for example, the tagName for 6ed09268cbdd0015bce8dcbbdfa9bfe4 is "img". The next line of code returns a list of all 6ed09268cbdd0015bce8dcbbdfa9bfe4 elements in the document:
var oImgs = document.getElementsByTagName("img");
After storing all graphics in oImgs, just use square brackets or Item() method (getElementsByTagName() returns a NodeList the same as childNodes), you can access these nodes one by one like accessing child nodes:
alert(oImgs[0].tagName); //outputs "IMG"
If you only want to get all the images in the first paragraph of a page, you can do it by calling getElementsByTagName() on the first paragraph element, like this:
var oPs = document.getElementByTagName("p") ;
var oImgsInp = oPs[0].getElementByTagName("img");
You can use an asterisk method to get all elements in the document:
var oAllElements = document.getElementsByTagName("*" );
When the parameter is an asterisk, IE6.0 does not return all elements. Document.all must be used instead.
(2)getElementsByName()
HTML DOM defines getElementsByName(), which is used to obtain all elements whose name attribute is equal to the specified value.
(3)getElementById()
这是HTML DOM定义的第二种方法,它将返回id特性等于指定值的元素。在HTML中,id特性是唯一的--这意味着没有两个元素可以共享同一个id。毫无疑问这是从文档树中获取单个指定元素最快的方法。
注:如果给定的ID匹配某个元素的name特性,IE6.0还会返回这个元素。这是一个bug,也是必须非常小心的一个问题。

5.创建新节点
最常用到的几个方法是
createDocumentFragment()--创建文档碎片节点
createElement(tagname)--创建标签名为tagname的元素
createTextNode(text)--创建包含文本text的文本节点

createElement()、createTextNode()、appendChild()

<html>
    <head>
        <title>createElement() Example</title>
        <script type="text/javascript">
            function createMessage() {
                var oP = document.createElement("p");
                var oText = document.createTextNode("Hello World!");
                oP.appendChild(oText);
                document.body.appendChild(oP);
            }
        </script>
    </head>
    <body onload="createMessage()">
    </body>
</html>

removeChild()、replaceChild()、insertBefore()
删除节点

<html>
    <head>
        <title>removeChild() Example</title>
        <script type="text/javascript">
            function removeMessage() {
                var oP = document.body.getElementsByTagName("p")[0];
                oP.parentNode.removeChild(oP);
            }
        </script>
    </head>
    <body onload="removeMessage()">
        <p>Hello World!</p>
    </body>
</html>

替换

<html>
    <head>
        <title>replaceChild() Example</title>
        <script type="text/javascript">
            function replaceMessage() {
                var oNewP = document.createElement("p");
                var oText = document.createTextNode("Hello Universe!");
                oNewP.appendChild(oText);
                var oOldP = document.body.getElementsByTagName("p")[0];
                oOldP.parentNode.replaceChild(oNewP, oOldP);
            }
        </script>
    </head>
    <body onload="replaceMessage()">
        <p>Hello World!</p>
    </body>
</html>

新消息添加到旧消息之前

<html>
    <head>
        <title>insertBefore() Example</title>
        <script type="text/javascript">
            function insertMessage() {
                var oNewP = document.createElement("p");
                var oText = document.createTextNode("Hello Universe!");
                oNewP.appendChild(oText);
                var oOldP = document.getElementsByTagName("p")[0];
                document.body.insertBefore(oNewP, oOldP);
            }
        </script>
    </head>
    <body onload="insertMessage()">
        <p>Hello World!</p>
    </body>
</html>

createDocumentFragment()
一旦把节点添加到document.body(或者它的后代节点)中,页面就会更新并反映出这个变化。对于少量的更新,这是很好的,然而,当要向document添加大量数据时,如果逐个添加这些变动,这个过程有可能会十分缓慢。为解决这个问题,可以创建一个文档碎片,把所有的新节点附加其上,然后把文档碎片的内容一次性添加到document中,假如想创建十个新段落。

<html>
    <head>
        <title>insertBefore() Example</title>
        <script type="text/javascript">
            function addMessages() {
                var arrText = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"];

                var oFragment = document.createDocumentFragment();

                for (var i=0; i < arrText.length; i++) {
                    var oP = document.createElement("p");
                    var oText = document.createTextNode(arrText[i]);
                    oP.appendChild(oText);
                    oFragment.appendChild(oP);
                }

                document.body.appendChild(oFragment);

            }
        </script>
    </head>
    <body onload="addMessages()">

    </body>
</html>

6.让特性像属性一样
大部分情况下,HTML DOM元素中包含的所有特性都是可作为属性。
假设有如下图像元素:
08eb671a6313b025fb2bd3d7f685f6c2
如果要使用核心的DOM来获取和设置src和border特性,那么要用getAttribute()和setAttribute()方法:
alert(oImg.getAttribute("src"));
alert(oImg.getAttribute("border"));
oImg.setAttribute("src","mypicture2.jpg");
oImg.setAttribute("border",1);
然而,使用HTML DOM,可以使用同样名称的属性来获取和设置这些值:
alert(oImg.src);
alert(oImg.border);
oImg.src="mypicture2.jpg";
oImg.border ="1";
唯一的特性名和属性名不一样的特例是class属性,它是用来指定应用于某个元素的一个CSS类,因为class在ECMAScript中是一个保留字,在javascript中,它不能被作为变量名、属性名或都函数名。于是,相应的属性名就变成了className;
注:IE在setAttribute()上有很大的问题,最好尽可能使用属性。
7.table方法
为了协助建立表格,HTML DOM给262fd5136f53c62e9a44a1fc2132297a,eb657ed06fa1cb552a30705c60d76f5d和bed2e7b14a405456e17405df6936f9bb等元素添加了一些特性和方法。
给262fd5136f53c62e9a44a1fc2132297a元素添加了以下内容:

特性/方法 说明
caption 指向f7a5eba2d0f16371ee005a8b211f0ae6元素并将其放入表格
tBodies eb657ed06fa1cb552a30705c60d76f5d元素的集合
tFoot 指向f396c81ab2d6506b0e1dd3149bd49748元素(如果存在)
tHead 指向123c34ba660610a744463a4eef99d319元素(如果存在)
rows 表格中所有行的集合
createTHead() 创建123c34ba660610a744463a4eef99d319元素并将其放入表格
createTFood() 创建f396c81ab2d6506b0e1dd3149bd49748元素并将其放入表格
createCpation() 创建f7a5eba2d0f16371ee005a8b211f0ae6元素并将其放入表格
deleteTHead() 删除123c34ba660610a744463a4eef99d319元素
deleteTFood() 删除f396c81ab2d6506b0e1dd3149bd49748元素
deleteCaption() 删除f7a5eba2d0f16371ee005a8b211f0ae6元素
deleteRow(position) 删除指定位置上的行
insertRow(position) 在rows集合中的指定位置上插入一个新行


eb657ed06fa1cb552a30705c60d76f5d元素添加了以下内容

特性/方法 说明
rows eb657ed06fa1cb552a30705c60d76f5d中所有行的集合
deleteRow(position) 删除指定位置上的行
insertRow(position) 在rows集合中的指定位置上插入一个新行
The


bed2e7b14a405456e17405df6936f9bb element adds the following content

特性/方法 说明
cells bed2e7b14a405456e17405df6936f9bb元素中所有的单元格的集合
deleteCell(postion) 删除给定位置上的单元格
insertCell(postion) 在cells集合的给点位置上插入一个新的单元格


8. Traverse the DOM
NodeIterator, TreeWalker
DOM Level2 functions, these functions are only available in Mozilla and Konqueror/Safari, and will not be introduced here.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:JSON study notesNext article:JSON study notes