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.
To add an ID attribute to the button, set a string value to the id property of button.
const button = document.createElement('button');
button.innerText = 'Button';
button.id = 'button-1';
box.appendChild(button);
Finally, add the button element to the box element.
Call the appendChild() method on the box by passing button as an argument.
Object.Assign()
Learn how to create the same HTML Elements using Object.assign()
Call the assign() method on the object inside appendChild().
Assign method takes two arguments:
- HTML DOM Element that we want to create
- A JavaScript object in which we can use any of the DOM properties such as id, innerHTML, etc.
document.body.appendChild(
Object.assign(
document.createElement('div'),
{ id : 'box'}
)
)
This is easier than the previous approach if we have a lot properties.
In order to add a child element to the box element, all we have to do is just chain another appendChild() with a button element.
Which is easier and more readable than the first approach.
document.body
.appendChild(
Object.assign(
document.createElement('div'),
{ id:'box'}
)
).appendChild(
Object.assign(
document.createElement('button'),
{ innerHTML : 'button' ,
id:'button-1'
}
)
)
ES 6 Backticks
Learn how to add the same HTML Elements to the DOM hierarchy using ES6 back-ticks which is by far the easiest.
Because, you can literally write HTML code inside JavaScript which is super easy to read and maintain.
Create a constant called box and add a pair of back-ticks. Write your HTML code exactly as you do inside the HTML page.
const box = ` <div id='box'> <button id='button-1'>Button</button> </div>`;document.body.innerHTML = box;
Assign it to the innerHTML property of the document.body.
That’s it.