<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
How to dynamically create
new elements in JavaScript?
</
title
>
<
style
>
/* CSS for child item */
.child {
color: white;
background-color: green;
}
</
style
>
</
head
>
<
body
id
=
"body"
>
<
h1
style
=
"text-align:center; color:green;"
>
GeeksforGeeks
</
h1
>
<
form
action
=
"#"
style
=
"text-align: center;"
>
<
label
for
=
"type"
>
Add Element Type
</
label
>
<
input
type
=
"text"
id
=
"type"
placeholder
=
"Like: div, h1, li...."
value
=
"h3"
/>
<
br
/><
br
/>
<
label
for
=
"value"
> Add Element Value</
label
>
<
input
type
=
"text"
id
=
"value"
placeholder
=
"Like: Hello GeeksForGeeks"
value
=
"Hello GeeksForGeeks"
/>
<
br
/><
br
/>
<
label
for
=
"attr"
> Add Attributes</
label
>
<
form
id
=
"attr"
>
<
label
for
=
"attrType"
>Add Attribute Type</
label
>
<
input
type
=
"text"
style
=
"width:240px;"
placeholder="forexample: enter
'class' without quotes"
id
=
"attrType"
value
=
"class"
/>
<
br
/>
<
br
/>
<
label
for
=
"attrValue"
>
Add Attribute Value
</
label
>
<
input
style
=
"width:240px;"
type
=
"text"
placeholder="for example: enter
'child' without quotes"
id
=
"attrValue"
value
=
"child"
/>
</
form
>
<
br
/><
br
/>
<
button
type
=
"button"
onClick
=
"addItem()"
>
Add
</
button
>
</
form
>
<
div
>
<
p
>CHILD 1</
p
>
</
div
>
<
script
>
// Define the addItem function
// to be called through onclick()
function addItem() {
// Get Elements by id of the form inputs
let parent =
document.getElementById("body");
let attrType =
document.getElementById("attrType");
let attrValue =
document.getElementById("attrValue");
let type = document.getElementById("type");
let value = document.getElementById("value");
if (type.value == "" || value.value == "") {
window.alert(
"There is an error in form input");
window.reload();
}
// createElement() method is used
// to create a new element
type = document.createElement(type.value);
// Append a text node for this example
type.appendChild(
document.createTextNode(value.value));
if (attrValue.value == ""
|| attrType.value == "") {
attr = null;
}
else {
// setAttribute() is used to set
// the attributes of the element
type.setAttribute(
attrType.value, attrValue.value);
}
// Append as child to the parent
// i.e. body
parent.appendChild(type);
}
</
script
>
</
body
>
</
html
>