2

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);
}
5
  • Are there any errors in your console? Why is the button outside of the form and still has type="submit"? Commented Jul 4, 2018 at 7:49
  • 1
    Possible duplicate of Adding a button, with onclick function, via javascript/jquery Commented Jul 4, 2018 at 7:50
  • Why do you have a submit button outside of a form? Commented Jul 4, 2018 at 7:51
  • I would feels like the better approach will be to add in the HTML element in the form, hide it, and use javascript to only shows the content of the hidden elements. Something like this: w3schools.com/howto/… Commented Jul 4, 2018 at 7:52
  • @Teemu I accidentally mixed up two approaches. I got rid off the submit and used the button outside of a form. This cleared a lot of errors. Commented Jul 4, 2018 at 7:59

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

Use Below,

 onclick="CreateNewDom()"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.