Dynamic Element creation is a common task in DOM. Next I will introduce how to use appendTo to dynamically create elements in jquery. For more information, see.
When the HTML string is an element without attributes, the document. createElement is used internally to create elements, for example:
// Use document. createElement to create an element in jQuery:
| The Code is as follows: |
Copy code |
$ ("Maid (" border "," solid 1px # FF0000 "Fig (" dynamically created div "). appendTo (testDiv );
|
Otherwise, use the innerHTML method to create elements:
// Use innerHTML to create an element in jQuery:
| The Code is as follows: |
Copy code |
$ ("Dynamically created div"). appendTo (testDiv) |
Let's look at a dynamic creation of DOM and form Element instances.
| The Code is as follows: |
Copy code |
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Html xmlns = "http://www.w3.org/1999/xhtml"> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Title> createElement </title> <Style type = "text/css"> . Warpper {border: 1px solid red; padding: 8px ;} </Style> <Script type = "text/javascript" language = "javascript" src = "JavaScript/jquery-1.6.1.min.js"> </script> <Script type = "text/javascript" language = "javascript"> <! -- /// Dynamically create a div $ (Function (){ $ ('<Div/> ',{ Id: 'test ', Text: "this is a div ", "Class": "warpper ", Click: function (){ Var text = $ (this). text (); Alert (text ); } }). AppendTo ("body "); }); // Create input: text $ (Function (){ $ ('<Input/> ',{ Type: "text ", Val: "input text somethings ...", Name: "userName" }). AppendTo ("body "); }); // Create input select $ (Function (){ Var slt = $ ('<select/>', {name: "country "}); $ ('<Option/> ',{ Val: "0 ", Text: "select" }). AppendTo (slt ); $ ('<Option> ',{ Val: "CN ", Text: "China ", Selected: "selected" }). AppendTo (slt ); $ ("Body"). append (slt ); }); // Create radio $ (Function (){ $ ('<Input/> ',{ Type: "radio ", Name: "rdo ", Checked: "checked ", Val: "male" }). AppendTo ("body "); $ ('<Label> ',{ Text: "male ", }). AppendTo ("body "); $ ('<Input/> ',{ Type: "radio ", Name: "rdo ", Val: "female" }). AppendTo ("body "); $ ('<Label> ',{ Text: "female" }). AppendTo ("body "); }); // Creat checkbox $ (Function (){ $ ('<Input/> ',{ Type: "checkbox ", Name: "cbox ", Val: "1 ", Checked: "checked" }). AppendTo ("body "); }); $ (Function (){ $ ('<Input/> ',{ Type: "file ", Name: "myfile" }). AppendTo ("body "); }); // --> </Script> </Head> </Body> </Html> |
If it is js, we can perform the following operations:
| The Code is as follows: |
Copy code |
Var select = document. createElement ("select "); Select. options [0] = new Option ("add-on 1", "value1 "); Select. options [1] = new Option ("add-on 2", "value2 "); Select. size = "2 "; TestDiv. appendChild (select ); }); |