During web development, JavaScript is often used to dynamically create HTML elements and set relevant attributes. For example, if you want to create a div layer, you can use the following Code .
1. directly establish Function Button1_onclick () // Directly create a div using code
{
VaR Newelement = Document. createelement ('div ');
VaR Newtext = Document. createtextnode ('This is the text in the newly created Div. ');
Document. Body. appendchild (newelement ); // This sentence is missing, otherwise it will not work
Newelement. ID = 'Newdiv ';
Newelement. classname = 'Newdidclass ';
Newelement. setattribute ('name', 'newdidname ');
Newelement. style. Width = '300px ';
Newelement. style. Height = '200px ';
Newelement. style. Margin = ' 0 Auto ';
Newelement. style. Border = '1px solid # DDD ';
Newelement. appendchild (newtext );
}
2. Write the new object into a common method to increase its universality. Createel = Function (T, A, Y, X) // Compile a common method for creating a new object
{
VaR E = Document. createelement (t );
Document. Body. appendchild (E ); // This sentence is missing, otherwise it will not work
If () {
For ( VaR K In A) {
If (K = 'Class') E. classname = A [k];
Else If (K = 'Id') E. ID = A [k];
Else E. setattribute (K, a [k]);
}
}
If (Y) { For ( VaR K In Y) E. Style [k] = Y [k];}
If (X) {E. appendchild (document. createtextnode (x ));}
Return E;
}
// Call the following method to create a new layer:
Function Button2_onclick () // First, the method of creating a new div is written as a general method, and then the DIV is instantiated by calling the method.
{
VaR Newelement = Createel ('div ',
{'Class': 'newdidclass', ID: 'newdiv ', name: 'newdidname '} ,
{Width: '300px ', height: '200px', margin :' 0 Auto', border: '1px solid # DDD '} ,
'This is the text in the newly created Div. ');
}
The two methods seem to use a long code block to achieve the same purpose. Actually, it is not, but the createei general method is more practical, the performance will be much better when similar objects are created.