Home > Web Front-end > JS Tutorial > Introduction to Javascript Chapter 9 Javascript DOM Summary_Basic Knowledge

Introduction to Javascript Chapter 9 Javascript DOM Summary_Basic Knowledge

PHP中文网
Release: 2016-05-16 19:03:15
Original
977 people have browsed it

As a js-DOM developer, you must know some DOM methods:

1, Create node.
createElement():
var a = document.createElement(“p”);
It creates an element node, so nodeType is equal to 1.
a.nodeName will return p;
Note; the new element node created by the createElement() method will not be automatically added to the document. Since it is not added to the document, it means that it is still in a free state. So it doesn't have nodeParent attribute either.
If you want to add it to the document, you can use the appendChild() or insertBefore() method or replaceChild() method. Of course, in the previous example, we wrote an insertAfter() method ourselves;
For example:
var a = document.createElement(“p”);
document.body.appendChild(a);
Note: appendChild() is added to the end of the document by default. That is, the lastChild child node.
If you want to add it somewhere, you can use insertBefore().
If you want to add attributes to the element before inserting it. You can do this:
var a = document.createElement(“p”);
a.setAttribute(“title”,”my demo”);
document.body.appendChild(a);

createTextNode():
var b = document.createTextNode(“my demo”);
It creates a text node, so nodeType is equal to 3.
b.nodeName will return #text ;
Like createElement(), nodes created with createTextNode() will not be automatically added to the document. You need to use the appendChild() or insertBefore() method or replaceChild() method.
He is often used in conjunction with createElement(), do you know why? (An element node, a text node.)
var mes = document.createTextNode(“hello world”);
var container = document.createElement(“p”);
container.appendChild(mes) ;
document.body.appendChild(container);


2, Copy the node.
cloneNode(boolean) :
It has one parameter.
var mes = document.createTextNode("hello world");
var container = document.createElement("p");
container.appendChild(mes);
document.body.appendChild( container);
var newpara = container.cloneNode(true);//The difference between true and false
document.body.appendChild(newpara);
Note:
true: it is Clone.
false: Only clone

, the text inside is not cloned.
You can write an example yourself and then use firebug to see it.

The new node after cloning, like createTextNode(), will not be automatically inserted into the document. AppendChild() is required;
Another note: If the id is the same after cloning, don’t forget to use setAttribute(“id”, “another_id “);
to change the ID of the new node.

3, Insert node.
appendChild():
Append a child node to the element, and insert the new node at the end.
var container = document.createElement("p");
var t = document.createTextNode("cssrain");
container.appendChild(t);
document.body.appendChild(container );
He is often used in conjunction with createElement(), createTextNode(), and cloneNode().
In addition, appendChild() can not only be used to append new elements, but also move existing elements in the document.
Look at the example below:

msg


content


aaaaaaaa


<script> <br>var mes = document.getElementById("msg"); <br>var container = document.getElementById("content"); <br> container.appendChild(mes); <br></script>
//I found that msg was placed behind content.
Js internal processing method:
First delete the one with ID msg from the document, and then insert it after content as the last node of content.
The result is:


content

msg



aaaaaaaa



insertBefore() :
As the name suggests, it inserts a new node in front of the target node.
Element.insertBefore( newNode , targerNode );

The second parameter is optional. If the second parameter is not written, it will be added to the end of the document by default, which is equivalent to appendChild();
Let’s see how insertBefore() is used:


1111


msg

test


222


aaaaaaaa



<script> <br>var msg = document.getElementById("msg"); <br>var aaa = document.getElementById("aaa"); <br>var test = document.getElementById("cssrian") ; <br>test.insertBefore( msg , aaa ); <br></script>
// We found that the ID of msg was inserted in front of aaa.
The internal processing method of Js is similar to appendChild().


4, Delete the node.
removeChild() :


a


< ;p id="b">b


c




<script> <br>var msg = document.getElementById("cssrain"); <br>var b = document.getElementById("b"); <br> msg.removeChild(b); <br> </script>
What if you don’t know what the parent node of the node to be deleted is? You can use the parentNode attribute.
For example:


a


b


c




<script> <br>var b = document.getElementById("b"); <br>var c = b.parentNode; <br>c.removeChild(b); <br></script>

Note: If you want to move a node from one place to another, you do not have to use removeChild().
You can use the previous appendChild() and insertBefore(), they will automatically delete the node first and then move it to the place you specify. ,


5, Replace the node.
Element.repalceChild( newNode , oldNode );
OldNode must be a child node of Element.


a


b


c




<script> <br>var cssrain = document.getElementById("cssrain"); <br>var msg = document.getElementById("b"); <br>var para = document.createElement("p"); <br>cssrain. replaceChild( para , msg ); <br></script>


6, Set/get the attribute node.
setAttribute();//Set
Example:
var a = document.createElement(“p”);
a.setAttribute(“title”,”my demo”);
Regardless of whether there was a title attribute before, the future value is my demo.

getAttribute();//Get
Example:
var a =document.getElementById(“cssrain”);
var b = a.getAttribute(“title”);
When obtaining, if the attribute does not exist, it will return empty. Note that the returns of ie and ff are different. You can see my previous example.
Although the returns are different, they can be judged by one method.
if(a.getAttribute(“title”)){ }


7,   Find the node.
getElementById();
Returns an object, which has properties such as nodeName, nodeType, parentNode, ChildNodes, etc.

getElementsByTagName() finds all elements of the tag name.
Returns a collection, and you can use a loop to take out each object. The object has properties such as nodeName, nodeType, parentNode, ChildNodes, etc.
Example:
var ps = document.getElementsByTagName(“p”);
for(var i=0; i< ps.length; i){
ps[i].setAttribute(“ title","hello");
//You can also use: ps.item(i).setAttribute("title","hello");
}


hasChildNodes:
You can know it by the name, it is a judgment Whether the element has child nodes.
Returns boolean type.
Text nodes and attribute nodes cannot have child nodes, so their hasChildNodes always returns false;
hasChildNodes is often used together with childNodes.
For example:


a


b


c




<script> <br>var ps = document.getElementById("cssrain") <br>if(ps.hasChildNodes){ <br> alert( ps.childNodes.length ); <br>} <br>< /script> <br><br>8, DOM attributes: <br>nodeName attribute: The name of the node. <br>If the node is an element node, return the name of the element. At this time, it is equivalent to the tagName attribute. <br>For example: <br><p>aaaa</p> : then returns p ; <br>If it is an attribute node, nodeName will return the name of this attribute. <br>If it is a text node, nodeName will return a #text string. <br><br>Another thing I want to say is: The nodeName attribute is a read-only attribute and cannot be set. (Write) <br><br>nodeType attribute: Returns an integer representing the type of this node. <br>We commonly use 3 types: <br>nodeType == 1 : Element node <br>nodeType == 2 : Attribute node <br>nodeType == 3 : Text node <br> If you want to remember, the above We can think of the order as from front to back. <br>For example: <p title="cssrain" >test</p> Read from front to back: You will find that there are element nodes first, then attribute nodes, and finally text nodes, so it is easy for you to remember What type does nodeType represent? <br><br>The nodeType attribute is often used in conjunction with if to ensure that the wrong operation is not performed on the wrong node type. <br>For example: <br>function cs_demo(mynode){ <br> if(mynode.nodeType == 1){ <br> mynode.setAttribute("title","demo"); <br> } <br> } <br> Code explanation: First check the nodeType attribute of mynode to ensure that the node it represents is indeed an element node. <br>Like the nodeName attribute, it is also a read-only attribute and cannot be set (write). <br><br><br><br>nodeValue attribute: Returns a string, the value of this node. <br>If the node is an element node, then null is returned; (note below) <br>If it is an attribute node, nodeValue will return the value of this attribute. <br>If it is a text node, nodeValue will return the content of this text node. <br>For example: <br><p id="c">aaaaaaaaaaaaaaaa</p> <br><SCRIPT LANGUAGE="JavaScript"> <br> var c= document.getElementById("c") ; <br> alert( c.nodeValue );//Return null <br></SCRIPT>
nodeValue is a property that can be read and written. But it cannot set the value of element node.
Look at the example below:

aaaaaaaaaaaaaaaa



Of course, in order to ensure correct operation: we can add a piece of code:

aaaaaaaaaaaaaaa



//요소 노드를 설정하려면 직접 설정할 수는 없지만 먼저 firstChild나 lastChild 등을 사용한 후 nodeValue를 설정해야 한다고 볼 수 있습니다.
nodeValue는 일반적으로 노드를 설정할 때만 사용됩니다. 텍스트 노드의 값입니다. 속성 노드의 값을 새로 고치려면 일반적으로 setAttribute()를 사용합니다.


childNodes 속성: 요소 노드의 하위 노드로 구성된 배열을 반환합니다.
텍스트 노드와 속성 노드는 더 이상 하위 노드를 포함할 수 없으므로
해당 childNodes 속성은 항상 빈 배열을 반환합니다.


요소에 하위 노드가 있는지 확인하는 데 사용되는 hasChildNodes 메서드를 사용할 수 있습니다.
또는 if (container.childNodes.length < 1)

childNodes도 읽기 전용 속성입니다. 노드를 추가하려면appendChild() 또는 insertBefore()를 사용할 수 있습니다.
노드를 삭제하려면 RemoveChild()를 사용할 수 있습니다. 작업 후 childNodes 속성이 자동으로 새로 고쳐집니다.

firstChild 속성:
텍스트 노드와 속성 노드는 더 이상 하위 노드를 포함할 수 없으므로
firstChild 속성은 항상 빈 배열을 반환합니다. 하위 노드가 없으면 null이 반환됩니다.
node.firstChild는 node.childNodes[0]과 동일합니다.
firstChild 속성은 읽기 전용 속성입니다.


lastChild 속성:
텍스트 노드와 속성 노드는 더 이상 하위 노드를 포함할 수 없으므로
lastChild 속성은 항상 빈 배열을 반환합니다. 하위 노드가 없으면 null이 반환됩니다.
node.lastChild는 node.childNodes[ node.childNodes.length - 1] 과 동일합니다.
lastChild 속성은 읽기 전용 속성입니다.

nextSibling 속성:
대상 노드의 다음 형제 노드를 반환합니다.
동일한 상위 노드에 속하는 대상 노드 뒤에 노드가 없으면 nextSibling은 null을 반환합니다.
nextSibling 속성은 읽기 전용 속성입니다.

previousSibling 속성:
대상 노드의 이전 형제 노드를 반환합니다.
동일한 상위 노드에 속하는 대상 노드 앞에 노드가 없으면 PreviousSibling은 null을 반환합니다.
이전 Sibling 속성은 읽기 전용 속성입니다.

parentNode 속성:
참고: 요소 노드에만 하위 노드가 있을 수 있으므로 parentNode 속성에서 반환되는 노드는 항상 요소 노드입니다.
물론 예외가 있습니다.
상위 노드가 없는 문서 노드입니다. 따라서 문서 노드의 parentNode 속성은 null을 반환합니다.
parentNode 속성은 읽기 전용 속성입니다.


source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template