I have been using JavaScript For a long time, and I am not familiar with the basic Dom methods. Well, I will try to learn it.
This evening I made a demo about the insertbefore method. The function is very simple. There are several P labels on the page. A drop-down list shows the number of P, then, a button inserts a text before the P tag.
The idea of demo programming is as follows: There are three functions in total: Init () is responsible for initialization and event binding. getpnum () is responsible for dynamically obtaining the number of P tags and filling them in the drop-down list, ADDP () is the main function implementation. My Code As follows:
Code
< Script Type = " Text/JavaScript " >
Window. onload = Init;
Function Init (){
Getpnum ();
Document. getelementbyid ( " ADDP " ). Onclick = Function () {ADDP ()};
}
Function Getpnum (){
VaR Pnum = Document. getelementsbytagname ( " P " ). Length;
For (I = 0 ; I < Pnum; I ++ )
{
Document. getelementbyid ( " Pnum " ). Options [I] = New Option (I + 1 , I + 1 );
}
}
Function ADDP (){
VaR Thepindex = Document. getelementbyid ( " Pnum " ). Selectedindex;
VaR Allp = Document. getelementsbytagname ( " P " );
VaR Insertob = Allp. Item (thepindex );
VaR Newp = Document. createelement ( " P " );
VaR Newtext = Document. createtextnode ( " This is in: " + New Date () + " The inserted text element! " );
Newp. appendchild (newtext );
Document. getelementbyid ( " Modifiable " ). Insertbefore (newp, insertob );
}
</SCRIPT>
After several debugging, I finally realized the function and had a deep understanding of insertbefor.
Usage of insertbefor:
Oelement
=
Object
. Insertbefore (
Onewnode
,
Ochildnode
)
Insert an element or text before the specified element. This requires two parameters to be passed when insertbefore is called. The first parameterOnewnode Is the element to be inserted, the second parameterOchildnode It is a coordinate element. For example, if there are four elements of ABCD and a text segment needs to be inserted before B, then parameter 2 is B. Note that at this timeOelementMust be the parent element of the Coordinate Function!
OchildnodeIs an optional parameter. If this parameter is not specified, it should be passed to ensure the compatibility of the Js in Firefox.NullGo in.
There are so many insertbefor statements :)