JavaScript Learning Notes: DOM node relationships and operations

Source: Internet
Author: User
Tags button type shallow copy tag name

0x01: Previous Words

The DOM can depict any HTML as a structure composed of multiple nodes. The nodes are divided into 12 different types, each representing different information and tags in the document. Each node has its own characteristics, data, and methods, and there is a relationship with other nodes. The relationships between nodes form a hierarchy, and all page markers appear as a tree structure with a specific node as the root node. This article describes in detail the node relationships between the DOM and the underlying DOM operations.

The relationships in the nodes can be described by the traditional family relationship, which is equivalent to the document tree metaphor. Next, the DOM node relationship is divided into the properties and methods of the two parts of the detailed description.

0X02: Properties

Parent Property
ParentNode

Each node has a ParentNode property that points to the parent node in the document tree. For a node, its parent node can be only three types: element node, document node, and DocumentFragment node. If it does not exist, NULL is returned.

    <div id="myDiv"></div><script>console.log(myDiv.parentNode);//bodyconsole.log(document.body.parentNode);//htmlconsole.log(document.documentElement.parentNode);//documentconsole.log(document.parentNode);//null</script>
<div id="myDiv"></div><script>var myDiv = document.getElementById(‘myDiv‘);console.log(myDiv.parentNode);//bodyvar fragment = document.createDocumentFragment();fragment.appendChild(myDiv);console.log(myDiv.parentNode);//document-fragment</script>

Parentelement

Unlike the ParentNode property, Parentelement returns the parent element node
<div id= "Mydiv" ></div>
<script>
Console.log (mydiv.parentelement);//body
Console.log (document.body.parentElement);//html
Console.log (document.documentElement.parentElement);//null
Console.log (document.parentelement);//null
</script>
[note] in IE, only element nodes have this attribute, and other browsers are all types of nodes that have this property

<div id="test">123</div><script>//IE浏览器返回undefined,其他浏览器返回<div id="test">123</div>console.log(test.firstChild.parentElement);//所有浏览器都返回<body>console.log(test.parentElement);</script>

Child properties
ChildNodes

ChildNodes is a read-only class Array object NodeList object that holds the first layer of child nodes of that node

<ul id="myUl"><li><div></div></li></ul><script>var myUl = document.getElementById(‘myUl‘);//结果是只包含一个li元素的类数组对象[li]console.log(myUl.childNodes);</script>

Children

Children is a read-only class Array object Htmlcollection object, but it holds the node's first-level element child node

<div id="myDiv">123</div><script>var myDiv = document.getElementById(‘myDiv‘);//childNodes包含所有类型的节点,所以输出[text]console.log(myDiv.childNodes);//children只包含元素节点,所以输出[]console.log(myDiv.children);</script>

Childelementcount

Returns the number of child element nodes, equivalent to Children.length

Note ie8-Browser does not support

<`ul` id="myUl">    <li></li>    <li></li></ul><script>var myUl = document.getElementById(‘myUl‘);console.log(myUl.childNodes.length);//5,IE8-浏览器返回2,因为不包括空文本节点console.log(myUl.children.length);//2console.log(myUl.childElementCount);//2,IE8-浏览器返回undefined</script>

FirstChild

First child node

LastChild

Last child node

Firstelementchild

First element child node

Lastelementchild

Last element child node

The above four properties, ie8-browser and standard browser performance is not consistent. Ie8-Browser does not consider blank text nodes and does not support Firstelementchild and Lastelementchild

There are two blank text nodes between the UL label and the LI tag, so according to the standard, the sub-nodes of UL include [blank text node, Li element node, blank text node]. However, in the Ie8-browser, UL's child nodes only include [LI element node]
<ul>
<li></li>
</ul>

<ul id="list">    <li>1</li>    <li>2</li>    <li>3</li></ul><script>console.log(list.firstChild);//标准浏览器中返回空白文本节点,IE8-浏览器中返回<li>1</li>console.log(list.lastChild);//标准浏览器中返回空白文本节点,IE8-浏览器中返回<li>3</li>console.log(list.firstElementChild);//标准浏览器中<li>1</li>,IE8-浏览器中返回undefinedconsole.log(list.lastElementChild);//标准浏览器中<li>3</li>,IE8-浏览器中返回undefined</script>

Sibling properties
NextSibling

The latter node

PreviousSibling

Previous node

Nextelementsibling

Next element node

Previouselementsibling

Previous element node

Similar to the child attributes, the above four properties do not match the performance of the Ie8-browser and the standard browser. Ie8-Browser does not consider blank text nodes and does not support nextelementsibling and previouselementsibling

<ul>    <li>1</li>    <li id="myLi">2</li>    <li>3</li></ul><script>var myLi = document.getElementById(‘myLi‘);console.log(myLi.nextSibling);//空白节点,IE8-浏览器返回<li>3</li>console.log(myLi.nextElementSibling);//<li>3</li>,IE8-浏览器返回undefinedconsole.log(myLi.previousSibling);//空白节点,IE8-浏览器返回<li>1</li>console.log(myLi.previousElementSibling);//<li>1</li>,IE8-浏览器返回undefined</script>

Method

Include method
HasChildNodes ()

The HasChildNodes () method returns True when it contains one or more child nodes, which is simpler than querying the length property of the ChildNodes list

<div id="myDiv">123</div><script>var myDiv = document.getElementById(‘myDiv‘);console.log(myDiv.childNodes.length);//1console.log(myDiv.hasChildNodes());//true</script><div id="myDiv"></div><script>var myDiv = document.getElementById(‘myDiv‘);console.log(myDiv.childNodes.length);//0console.log(myDiv.hasChildNodes());//false</script>

Contains ()

The Contains method takes a node as a parameter and returns a Boolean value that indicates whether the parameter node is the descendant node of the current node. parameter is a descendant node, not necessarily the first-level child node

<div id="myDiv">    <ul id="myUl">        <li id="myLi"></li>        <li></li>    </ul></div><script>console.log(myDiv.contains(myLi));//trueconsole.log(myDiv.contains(myUl));//trueconsole.log(myDiv.contains(myDiv));//true</script>

Note IE and Safari do not support the Document.contains () method, only the contains () method that supports ELEMENT nodes

IE and Safari error, other browsers return True
Console.log (Document.contains (document.body));

Relationship method
Comparedocumentposition ()

The Comparedocumentposition method is used to determine the relationship between nodes, returning a bitmask that represents the relationship

000000    0     两个节点相同000001    1     两个节点不在同一个文档(即有一个节点不在当前文档)000010    2     参数节点在当前节点的前面000100    4     参数节点在当前节点的后面001000    8     参数节点包含当前节点010000    16    当前节点包含参数节点100000    32    浏览器的私有用途
<div id="myDiv">    <ul id="myUl">        <li id="myLi1"></li>        <li id="myLi2"></li>    </ul></div><script>

20=16+4, because the Myul node is contained by the MYDIV node and is also behind the Mydiv node
Console.log (Mydiv.comparedocumentposition (Myul));

10=8+2, because the Mydiv node contains MYUL nodes, also in front of the Myul node
Console.log (Myul.comparedocumentposition (mydiv));

0, two nodes are the same
Console.log (Mydiv.comparedocumentposition (mydiv));

4,myli2 at the back of the MYLI1 node
Console.log (Myli1.comparedocumentposition (MYLI2));

2,myli1 in front of the MYLI2 node
Console.log (Myli2.comparedocumentposition (MYLI1));
</script>

Issamenode () and Isequalnode ()

Both of these methods accept a node parameter and return TRUE if the incoming node is the same or equal to the reference node

The so-called Same (same) refers to the same object that is referenced by two nodes

The so-called equality (equal), refers to the two nodes are the same type, with equal attributes (NodeName, NodeValue, and so on), and their attributes and ChildNodes attributes are equal (the same position contains the same value)

[Note]firefox does not support the Issamenode () method, and Ie8-browser two methods do not support

<script>var div1 = document.createElement(‘div‘);div1.setAttribute("title","test");var div2 = document.createElement(‘div‘);div2.setAttribute("title","test");console.log(div1.isSameNode(div1));//trueconsole.log(div1.isEqualNode(div2));//trueconsole.log(div1.isSameNode(div2));//false</script>
0x03:dom node operation

Generally, the lifting operation will think of "add and Delete to change" The four words, and DOM node operation similarly corresponds to this, next will detail the DOM node operation method.
Premise
The DOM provides a way to manipulate nodes because the DOM node relationship pointers are read-only

The following code wants to modify its node relationship by modifying the parent node of the Myul, but because the ParentNode property is read-only, the modification is invalid and even an error in the Ie8-browser

<div id="myDiv"></div><ul id="myUl">    <li id="myli"></li></ul><script>console.log(myUl.parentNode);//<body>myUl.parentNode = myDiv;//标准浏览器下,依然返回<body>;而IE8-浏览器则会报错console.log(myUl.parentNode);</script>

DOM node action methods include creating nodes, inserting nodes, deleting nodes, replacing nodes, viewing nodes, and replicating nodes. View node refers to the view of the relationship between nodes, in the node relationship section has been described in detail, will not repeat

Create a Node
CreateElement ()

The Document.createelement () method can create a new element. This method takes a parameter that is to create the tag name of the element, which is not case-sensitive in the HTML document

var oDiv = document.createElement("div");console.log(oDiv);//<div>

The ie8-browser can pass in the full element tag for this method, or it can contain attributes

var oDiv = document.createElement(‘<div id="box"></div>‘);console.log(oDiv.id);//‘box‘

Using this approach, you can avoid the following issues with ie7-browsers creating elements dynamically

1. Cannot set the name attribute of dynamically created <iframe> element

2. Dynamically created <input> elements cannot be reset by the Reset () method of the form

3, dynamic creation of the type attribute value of "reset" <button> element is not reset form

4. Dynamically created batch name of the same radio button has nothing to do with each other. A set of radio buttons with the same name value should be used to represent different values for the same option, but there is no such relationship between a batch of dynamically created radio buttons

var iframe = document.createElement("<iframe name = ‘myframe‘></iframe>");var input = document.createElement("<input type=‘checkbox‘>);var button = document.createElement("<button type = ‘reset‘></button>");var radio1 = document.createElement("<input type=‘radio‘ name =‘choice‘ value = ‘1‘>");var radio2 = document.createElement("<input type=‘radio‘ name =‘choice‘ value = ‘2‘>");

All nodes have a ownerdocument property that points to the document node that represents the entire document, and the Ownerdocument property is set for the new element while creating the new element using the CreateElement () method

<div id="myDiv"></div><script>console.log(myDiv.ownerDocument);//documentvar newDiv = document.createElement(‘div‘);console.log(newDiv.ownerDocument);//documentconsole.log(newDiv.ownerDocument === myDiv.ownerDocument);//true</script>

Inserting nodes
AppendChild ()

The AppendChild () method adds a node to the end of the ChildNodes list and returns the new node. When a node is added, the relationship pointers to the new, parent, and previous last child nodes in ChildNodes are updated accordingly

<div id= "box" ></div>
<script>
var OBox = document.getElementById (' box ');
var newNode = document.createelement (' ul ');
var returnednode = Obox.appendchild (NewNode);
Console.log (returnednode.nodename);//ul
Console.log (Returnednode = = NewNode);//true
Console.log (Returnednode = = Obox.lastchild);//true
</script>

If the inserted node is already part of the document, the result is to move the node from its original location to the new location

<body><div id="oldDiv">第一个div</div><div id="newDiv">第二个div</div><button id="btn">变换位置</button><script>btn.onclick = function(){    document.body.appendChild(newDiv);}    </script></body>

InsertBefore ()

The InsertBefore () method receives two parameters: the node to be inserted and the node that is the reference. When the node is inserted, the inserted node becomes the previous sibling node (previoussibling) of the reference node and is returned by the method. If the reference node is null, then InsertBefore () performs the same operation as the AppendChild () method. Similarly, if the inserted node is already part of the document, the result is to move the node from its original location to the new location

ReferenceNode.parentNode.insertBefore (Newnode,referencenode);

<ul id="myUl" style="border:1px solid black;">    <li id="myLi">        <div id=‘oldDiv‘>oldDiv</div>    </li>    </ul><button id="btn1">插入oldDiv的前面</button><button id="btn2">插入myUl的前面</button><button id="btn3">插到oldDiv的里面</button><script>var oDiv = document.createElement(‘div‘);oDiv.innerHTML = ‘newDiv‘;btn1.onclick = function(){    console.log(myLi.insertBefore(oDiv,oldDiv));//<div>newDiv</div>}btn2.onclick = function(){    console.log(document.body.insertBefore(oDiv,myUl));//<div>newDiv</div>}btn3.onclick = function(){    console.log(oldDiv.insertBefore(oDiv,null));//<div>newDiv</div>}</script>

"Small Effect"

<ul class="list" id="list">    <li class="in">1</li>    <li class="in">2</li>    <li class="in">3</li>    <li class="in">4</li>    <li class="in">5</li>    <li class="in">6</li>        </ul><script>var oList = document.getElementById(‘list‘);//新增一个li元素var oAdd = document.createElement(‘li‘);//设置新增元素的css样式oAdd.className = "in";oAdd.style.cssText = ‘background-color:red;border-radius:50%‘;//添加到oList中oList.insertBefore(oAdd,null);var num = -1;var max = oList.children.length;function incrementNumber(){    num++;    //oList.getElementsByTagName(‘li‘)[max]相当于null,所以不报错    oList.insertBefore(oAdd,oList.getElementsByTagName(‘li‘)[num]);        if(num == max){        num = -1;    }        if(num == 0){        num = 1;    }    setTimeout(incrementNumber,1000);}setTimeout(incrementNumber,1000);</script>

InsertAfter ()

Because there is no InsertAfter () method, you can use the InsertBefore () and appendchild () encapsulation methods if you want to interpolate behind a child node of the current node

function insertAfter(newElement,targetElement){    var parent = targetElement.parentNode;    if(parent.lastChild == targetElement){        parent.appendChild(newElement);    }else{        parent.insertBefore(newElement,targetElement.nextSibling)    }}
<div id=‘oldDiv‘>old</div><button id="btn">增加节点</button><script>function insertAfter(newElement,targetElement){    var parent = targetElement.parentNode;    if(parent.lastChild == targetElement){       return parent.appendChild(newElement);    }else{       return parent.insertBefore(newElement,targetElement.nextSibling)    }}    var newDiv = document.createElement(‘div‘);newDiv.innerHTML = ‘new‘;btn.onclick = function(){    insertAfter(newDiv,oldDiv);}</script>

insertAdjacentHTML ()

The insertAdjacentHTML () method, as an end-level approach, is equivalent to the synthesis of the previous three methods. The method receives two parameters: the inserted position and the HTML text to be inserted

The first parameter must be one of the following values, and these values must be in lowercase:

"Beforebegin" Inserts an immediate sibling element before the current element
"Afterbegin" Inserts a new child element below the current element or inserts a new child element before the first child element
"BeforeEnd" Inserts a new child element below the current element or inserts a new child element after the last child element
"Afterend" Inserts an immediate sibling element after the current element
The second argument is an HTML string that throws an error if the browser cannot parse the string

[note] The method has no return value

<div id=‘target‘ style="border: 1px solid black;">This is the element content</div><button>beforebegin</button><button>afterbegin</button><button>beforeend</button><button>afterend</button><script>var btns = document.getElementsByTagName(‘button‘);for(var i = 0 ; i < 4; i++){    btns[i].onclick = function(){        var that = this;        target.insertAdjacentHTML(that.innerHTML,‘<span id="test">测试</span>‘)        }}</script>    

removing nodes
RemoveChild ()

The RemoveChild () method takes a parameter that is the node to be removed, and the removed node becomes the return value of the method

<div id="myDiv">等待移除的节点</div><button id="btn">移除节点</button><script>btn.onclick = function(){    document.body.removeChild(myDiv);}</script>

  

Remove ()

The Remove () method is less common than removechild (), but it is very simple. Instead of calling its parent, the method can delete the node directly at the current node using the Remove () method, with no return value

The Remove () method is commonly used to delete element nodes and text nodes, not for attribute nodes

Note This method is not supported by IE browser

<div id="test" title=‘div‘>123</div><script>//文本节点console.log(test.childNodes[0]);//‘123‘test.childNodes[0].remove();console.log(test.childNodes[0]);//undefined//特性节点console.log(test.attributes.title);//‘div‘//报错,remove()方法无法用于删除特性节点try{test.attributes[0].remove()}catch(e){    console.log(‘error‘);}//元素节点console.log(test);test.remove();</script>

Replace node
ReplaceChild ()

The two parameters received by ReplaceChild () are the node to be inserted and the node to be replaced, the node to be replaced is returned by this method and removed from the document tree, occupying its position by the node to be inserted

OldChild.parentNode.replaceChild (NewChild, oldchild);

<div id="div1">1</div><div id="div2">2</div><div id="div3">3</div><button id="btn1">新增节点替换(4替换2)</button><button id="btn2">原有节点替换(3替换1)</button><script>btn2.onclick = function(){    document.body.replaceChild(div3,div1);}btn1.onclick = function(){    var div4 = document.createElement(‘div‘);    div4.innerHTML = ‘4‘;    document.body.replaceChild(div4,div2);}</script>

Replication nodes
CloneNode ()

The CloneNode method is used to clone a node. It takes a Boolean value as a parameter that indicates whether to perform a deep copy. When the parameter is true, a deep copy is performed, that is, the copy node and the entire child node tree. In the case where the parameter is false, a shallow copy is performed, that is, the node itself is copied. The copy of the node returned after replication belongs to the document, but does not specify a parent node for it. If the argument is empty, it is also equivalent to False

[Note the]clonenode () method does not copy JavaScript attributes that are added to the DOM node, such as event handlers. This method only copies the attributes and child nodes, and nothing else is copied

<ul id="list">    <li>1</li>    <li>2</li>    <li>3</li>    <li>4</li>    <li>5</li>    <li>6</li>        </ul><script>var oList = document.getElementById(‘list‘);oList.index = 0;var deepList = oList.cloneNode(true);//成功复制了子节点console.log(deepList.children.length);//6//但并没有复制属性console.log(deepList.index);//undefinedvar shallowList = oList.cloneNode();//浅复制不复制子节点console.log(shallowList.children.length);//0</script>

JavaScript Learning Notes: DOM node relationships and operations

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.