3 Ways To Create HTML Element In JavaScript
Learn how to create html element in JavaScript in a few different ways
- Using just createElement()
- Object.assign()
- ES6 Backticks
Using Just createElement()
Create a div HTML Element in JavaScript by calling the createElement() method on the document object.
This method takes an argument which will be the HTML Element.
In this case…div.
const box = document.createElement("div");
box.id = "box";
document.body.appendChild(box);
Assign it to the constant called box.
Set the id property of box to ‘box‘.
Add it to the DOM hierarchy by calling appendChild() on the document.body object with an argument box.
Let’s add a child element to the box element.
To do that, create a button HTML Element in JavaScript by calling the createElement() method on the document object.
This method takes an argument…
but this time, button.
Assign it to the constant called button.
Add text to the button element by setting a string value to the innerHTML property of it.
Append the button element to the DOM hierarchy by calling the appendChild() method on the document.body object with button as an argument.