Reputation:
I want to create a HTML-Element by pressing on a Button on the same page, but the Element won't appear after clicking.
my HTML:
<button type="submit" name="e-h1" onclick="CreateNewDom">H1 Überschrift</button>
<form id="editor" method="post">
</form>
and my JS:
function CreateNewDom() {
var DOMHeadingOne = document.createElement("input");
DOMHeadingOne.setAttribute("type", "text");
DOMHeadingOne.classList.add("e-h1");
document.getElementById("editor").appendChild(DOMHeadingOne);
}
My goal is to be able to create a custom form, so I will need to be able to create multiple Elements by clicking their respective buttons. Since I'm a total newbie I can't get my head wrapped around the right way to approach my problem.
Hints to the final approach are welcome.
EDIT: Problem solved. I accidentally mixed up two approaches to the Problem. Code works fine like this: HTML:
<button name="e-h1" onclick="CreateNewDom()">H1 Überschrift</button>
<form id="editor" method="post">
</form>
JS:
function CreateNewDom() {
var DOMHeadingOne = document.createElement("input");
DOMHeadingOne.setAttribute("type", "text");
DOMHeadingOne.classList.add("e-h1");
document.getElementById("editor").appendChild(DOMHeadingOne);
}
Upvotes: 2
Views: 2030
Reputation: 580
You were not calling the function correctly in the HTML. Changing onclick="CreateNewDom"
to onclick="CreateNewDom();"
fixed the issue
function CreateNewDom() {
var DOMHeadingOne = document.createElement("input");
DOMHeadingOne.setAttribute("type", "text");
DOMHeadingOne.classList.add("e-h1");
document.getElementById("editor").appendChild(DOMHeadingOne);
}
<button type="submit" name="e-h1" onclick="CreateNewDom();">H1 Überschrift</button>
<form id="editor" method="post">
</form>
Upvotes: 1