To insert a node:
1). InsertBefore (): Inserts a given node in front of a given child node of a given element node
var reference = Element.insertbefore (Newnode,targetnode);
The node NewNode will be inserted into the element node elements and appear in front of the node TargetNode. The node TargetNode must be a child node of element elements.
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Inserting nodes</title>6 <Scripttype= "Text/javascript">7 //Test insertbefore () Insert node8 //besides inserting, the method also has the function of moving node.9 window.onload=function(){Ten //1. Insert the #rl in front of the #bj node One varCitynode=document.getElementById (" City"); A varBjnode=document.getElementById ("BJ"); - varRlnode=document.getElementById ("RL"); - the Alert ("Test started.") - //Citynode.insertbefore (Rlnode,bjnode);//(New, target node) - - + //test Method - varRefnode=document.getElementById ("DJ"); + Insetafter (rlnode,refnode); A } at - - //Write a Insetafter method/insert the NewNode into the back of the Refnode - functionInsetafter (newnode,refnode) { - //1. Test whether the Refnode is the last child node of its parent node - varparentnode=Refnode.parentnode; in if(parentnode) { - varLastnode=Parentnode.lastchild; to //2. If: Insert NewNode directly into the last child node of the Refnode parent node + if(Refnode==lastnode) { - Parentnode.appendchild (newNode); the } * $ //3. If not: Gets the next sibling node of the Refnode and then inserts it in front of its next sibling node.Panax Notoginseng Else{ - varNextNode=refnode.nextsibling; the Parentnode.insertbefore (newnode,nextnode); + } A } the } + </Script> - </Head> $ <Body> $ <P>Which city do you like?</P> - <ulID= "City"><LiID= "BJ"name= "Beijing">Beijing</Li> - <Li>Shanghai</Li> the <LiID= "DJ">Tokyo</Li> - <LiID= "se">Seoul</Li>Wuyi </ul> the - <BR><BR> Wu <P>Which stand-alone game do you like?</P> - <ulID= "Game"> About <LiID= "RL">Red Police</Li> $ <Li>Live</Li> - <Li>Need for Speed</Li> - <Li>Warcraft</Li> - </ul> A + <BR><BR> the Gender: - <inputtype= "Radio"name= "Gender"value= "Male"/>Male $ <inputtype= "Radio"name= "Gender"value= "female"/>Female the the <BR><BR> theName<inputtype= "text"name= "username"value= "Atguigu"/> the - </Body> in </HTML>
JavaScript DOM programming--11--inserting nodes