1<!DOCTYPE HTML>
2<html>
3
4<head>
5 <title>
6 How to dynamically create
7 new elements in JavaScript?
8 </title>
9</head>
10
11<body>
12 <h1 style="text-align:center; color:green;">
13 GeeksForGeeks
14 </h1>
15
16 <!-- Form to add item -->
17 <form action="#" style="text-align:center;">
18
19 <!-- Type of Element -->
20 <label for="type">
21 Add Element Type
22 </label>
23
24 <input type="text" id="type"
25 placeholder="Like: div, h1, li...."
26 value="li" />
27 <br /><br />
28
29 <!-- Text/Value for the element --->
30 <label for="value">
31 Add Element Value
32 </label>
33
34 <input type="text" id="value"
35 placeholder="Like: Hello GeeksForGeeks"
36 value="CHILD 2" />
37 <br /><br />
38
39 <!-- Submit the Form -->
40 <button type="button"
41 onClick="addItem()">
42 Add
43 </button>
44 </form>
45
46 <!-- Parent tag where we add
47 item as child -->
48 <ol id="parent">
49 <li>List Item 1</li>
50 </ol>
51
52 <script>
53
54 // Define the addItem() function
55 // to be called through onclick
56 function addItem() {
57
58 // Get type of element from form
59 let type = document.
60 getElementById("type").value;
61
62 // Get the text/value for the tag
63 // from the form
64 let value = document.
65 getElementById("value").value;
66
67 // createElement() is used for
68 // creating a new element
69 type
70 = document.createElement(type);
71
72 // Use value as textnode in this example
73 type.appendChild(
74 document.createTextNode(value));
75
76 // Append as child to the parent
77 // tag i.e. ol
78 document.getElementById(
79 "parent").appendChild(type);
80 }
81 </script>
82</body>
83
84</html>
85