In this shot, we will how learn to create a new HTML element dynamically, which HTML is running.
HTML DOM provides us with several methods to work with the DOM tree and other elements. In this shot, we will use the document.createElement()
method, which creates a new HTML element.
document.createElement(Element_name)
Element_name
: Name of the element you want to create. For example, "div"
, "p"
, "img"
, "button"
.Object
: This will return an element object like other HTML objects with all the attributes it has or has already defined.We have two files. One is HTML, and one contains JavaScript code.
In the HTML file, we write a code to display text using the <p>
tag and a button using the <button>
tag. This button will call a "myFunc()"
function when we click the button.
This myFunc()
function is defined in our JavaScript file.
In the JavaScript file, we define a function myFunc()
which will be called upon the click of a button in the HTML page.
In line 2, we created an HTML element using document.createElement()
, which takes a parameter of the element’s name. Here, we are creating a button
element, so we passed button
. You can also try other names like p
, div
, or any HTML element name.
This will return an HTML element, and we will store it in the variable btn
.
In the next line, we are inserting text in the btn
element by using the HTML property element.innerHTML
.
In the last line, we need to insert/append this element in the DOM tree. We will use the HTML method document.body.appendChild(btn)
, which will append the element btn
in the body
of HTML.