DOM Node action method

Source: Internet
Author: User

Read-Only relationship pointers

The relationship pointers in the DOM are read-only

<div class= "box" id= "box" ></div><script>var oBox = document.getElementById (' box '); Console.log (oBox.parentNode.nodeName); // BODY // in the ie8-browser will be error, in other browsers ignore this statement Obox.parentnode = document;console.log (oBox.parentNode.nodeName); // BODY</script>

Operation method

"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 class= "box" id= "box" ></div><script>var oBox = document.getElementById (' box '); var newNode = document.createelement (' ul '); var returnednode = obox.appendchild (newNode); Console.log (returnednode.nodename); // ULconsole.log (Returnednode = = NewNode); // trueconsole.log (Returnednode = = Obox.lastchild); // true</script>

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

<ul class= "list" id= "list" > <li class= "in" >1</li> <li class= "in" >2</li> <li clas S= ' in ' >3</li> <li class= ' in ' >4</li> <li class= ' in ' >5</li> <li class= ' in ' >6 </li> </ul><script>varOlist = document.getElementById (' list ');//Add an LI elementvarOadd = document.createelement (' li ');//set CSS styles for new elementsOadd.classname = "in"; OAdd.style.cssText= ' background-color:red;border-radius:50% ';//Add to OlistOlist.insertbefore (Oadd,NULL);varnum =-1;varMax =oList.children.length;functionincrementnumber () {num++; //olist.getelementsbytagname (' li ') [max] equals null, so no errorOlist.insertbefore (oadd,olist.getelementsbytagname (' Li ')) [num]); if(num = =max) {num=-1; }        if(num = = 0) {num= 1; } setTimeout (Incrementnumber,1000);} SetTimeout (Incrementnumber,1000);</script>

"InsertAfter () package"

There is no InsertAfter () method in native JavaScript, but it is possible to use the InsertBefore () and appendchild () encapsulation methods

function InsertAfter (newelement,targetelement) {    var parent = Targetelement.parentnode;     if (Parent.lastchild = = targetelement) {        parent.appendchild (newelement);    } Else {        parent.insertbefore (newelement,targetelement.nextsibling)    }}
<ul class= "list" id= "list" > <li class= "in" >1</li> <li class= "in" >2</li></ul>< Script>functionInsertAfter (newelement,targetelement) {varParent =Targetelement.parentnode; if(Parent.lastchild = =targetelement)    {Parent.appendchild (newelement); }Else{Parent.insertbefore (newelement,targetelement.nextsibling)}}varOlist = document.getElementById (' list ');varOLi2 = Olist.getelementsbytagname ("li") [1];varNewelement = document.createelement ("li"); InsertAfter (Newelement,oli2); Console.log (olist.childnodes) ;//returned under standard browser [text, li.in, text, li.in, Li, text], without a blank text node under ie8-browser</script>

"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

<ul class= "list" id= "list" > <li class= "in" >1</li> <li class= "in" >2</li> <li clas S= ' in ' >3</li> <li class= ' in ' >4</li> <li class= ' in ' >5</li> <li class= ' in ' >6 </li> </ul><script>varOlist = document.getElementById (' list ');functionIncrementnumber () {//gets the number of neutron elements in the olist    varLen = olist.getelementsbytagname (' li '). length; //If the length is not 0    if(len) {//Delete Last child elementOlist.removechild (olist.getelementsbytagname (' Li ') [len-1]); //Call the timer againSetTimeout (incrementnumber,1000); }}//1s post-execution function IncrementnumberSetTimeout (incrementnumber,1000);</script>

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

<ul class= "list" id= "list" > <li class= "in" >1</li> <li class= "in" >2</li> <li clas S= ' in ' >3</li> <li class= ' in ' >4</li> <li class= ' in ' >5</li> <li class= ' in ' >6 </li> </ul><script>varOlist = document.getElementById (' list ');functionIncrementnumber () {//gets the number of neutron elements in the olist    varLen = olist.getelementsbytagname (' li '). length; //If the length is not 0    if(len) {//Delete Last child elementOlist.removechild (olist.getelementsbytagname (' Li ') [len-1]); //Call the timer againSetTimeout (incrementnumber,1000); }}//1s post-execution function IncrementnumberSetTimeout (incrementnumber,1000);</script>

"CloneNode ()"

The CloneNode method is used to create an identical copy of the node that invokes the method, which receives a Boolean parameter that indicates whether deep replication is performed. 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 (in the case of explicit replication) child nodes, nothing else is copied.

<ul class= "list" id= "list" > <li class= "in" >1</li> <li class= "in" >2</li> <li clas S= ' in ' >3</li> <li class= ' in ' >4</li> <li class= ' in ' >5</li> <li class= ' in ' >6 </li> </ul><script>varOlist = document.getElementById (' list ');varDeeplist = Olist.clonenode (true);/*ie8-Unlike other browsers that handle whitespace characters, ie8-does not create a node for the whitespace character*/Console.log (deepList.childNodes.length);//ie8-is 6, other browsers areDocument.body.insertBefore (deeplist,olist);varShallowlist =Olist.clonenode (); Console.log (shallowList.childNodes.length);//0</script>

"insertAdjacentHTML ()"

The insertAdjacentHTML () 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", inserting 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", inserting 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

<div class= "box" id= "box" > I am the initial element </div><script>var oBox = document.getElementById (' box ' ); obox.insertadjacenthtml ("Beforebegin", "<p> I am the new ex-brother element </p>") obox.insertadjacenthtml ( "Afterbegin", "<p> I am the new front child element </p>") obox.insertadjacenthtml ("BeforeEnd", "<p> I am the new post child element </p> "obox.insertadjacenthtml" ("Afterend", "<p> I am the new post-sibling element </p>")</ Script>
/* The screen results show that I am the new ex-sibling element I am the new former child element I am the original element I am the new   post-child element I am the new post-sibling element * /

Precautions

"Note 1" If the node passed into AppendChild (), ReplaceChild (), InsertBefore () is already part of the document, move the node from its original location to the new location

<ul class= "list" id= "list" > <li class= "in" >0</li> <li class= "in" id= "test" >test</li> <li class= "in" >2</li></ul><script>varOlist = document.getElementById (' list ');varOtest = document.getElementById (' Test ');d Ocument.onclick=function(){    //after clicking on the document, the order of three Li changes from 0 test 2 to 0 2 testOlist.appendchild (otest); SetTimeout (function(){        //after 1s, the order of three Li becomes 2 0 testOlist.insertbefore (document.getelementsbytagname (' li ') [0],otest); SetTimeout (function(){            //after 1s, there are only two Li, and the order is test 0Olist.replacechild (otest,document.getelementsbytagname (' li ') [0]); },1000); },1000);}</script>

"Note 2" Dynamic considerations

"1" in the case of variable storage

<ul class= "list" id= "list" >    <li class= "in" >1</li>    <li class= "in" >2</li>    <li class= "in" >3</li></ul><script>var olist = document.getElementById (' list ') ; // oIn0 points to the No. 0 object, not the No. 0 position. var oIn0 = olist.getelementsbytagname ("li") [0];console.log (oin0.innerhtml); // 1 // OIn0 points to the original No. 0 object, but changes from the No. 0 position to the 2nd position, Olist.appendchild (oIn0); Console.log (oin0.innerhtml); // 1</script>

"2" in the case of non-existence of variables

<ul class= "list" id= "list" >    <li class= "in" >1</li>    <li class= "in" >2</li>    <li class= "in" >3</li></ul><script>var olist = document.getElementById (' list ') ; // gets the No. 0 position of the object Console.log (olist.getelementsbytagname ("Li") [0].innerhtml); // 1 // changes the object in position No. 0 to the 2nd position Olist.appendchild (olist.getelementsbytagname ("Li") [0]); // re-acquires the No. 0 position of the object Console.log (olist.getelementsbytagname ("Li") [0].innerhtml); // 2</script>

DOM Node action method

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.