What is the HTML document.createElement() method?
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.
Syntax
document.createElement(Element_name)
Parameters
Element_name: Name of the element you want to create. For example,"div","p","img","button".
Return value
Object: This will return an element object like other HTML objects with all the attributes it has or has already defined.
Code
Explanation
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 abuttonelement, so we passedbutton. You can also try other names likep,div, or any HTML element name. This will return an HTML element, and we will store it in the variablebtn. -
In the next line, we are inserting text in the
btnelement by using the HTML propertyelement.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 elementbtnin thebodyof HTML.