23
Beginner JavaScript - 14 - Creating and Inserting Elements to the DOM
Hey everyone 👋🏻,
In this article, let us discuss about Creating, Inserting and Removing Elements from the DOM in JavaScript. This is the fourteenth part of my Beginner JavaScript Series on Dev.
Let us first discuss about creating and inserting elements in DOM before we move our attention to removing elements.
For creating and inserting elements in DOM, I would live to cover basically two ways :
Let us first talk about HTML Strings :
The innerHTML property sets or returns the HTML content (inner HTML) of an element.
// Let us assume we want to add some html markup inside some element with the id of x12
const markup = `<div>
<h1>This is some dummy markup </h1>
</div>
`;
document.getElementById("x12").innerHTML = markup;
The insertAdjacentHTML() method parses (goes over) the given HTML code and inserts the specified nodes that we create into the DOM tree at a specified position. The benefit of using insertAdjacentHTML is that it does not reparse the element it is being used on, so it saves the cost of re-initiating this step and thus it avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.
SYNTAX
element.insertAdjacentHTML(position, text);
// Let us assume we want to add some html markup inside some element with the id of x12
const markup = `<div>
<h1>This is some dummy markup </h1>
</div>
`;
document.getElementById("x12").innerHTML = markup;
The document.createElement() method is used to create a new HTML element and attach it to a DOM tree.
Let us see the syntax for creating an element using the document.createElement method.
const element = document.createElement(elementType);
Let us see the examples for appendChild and append methods.
Let us say our starter HTML is this :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>append and appendChild methods</title>
</head>
<body>
</body>
</html>
Let us create a div element using the document.createElement method and then make use of the appendChild method to add the newly created div to the body of the HTML.
const div = document.createElement('div');
div.innerHTML = '<p>This is a div element</p>';
// Append the div as a child element to the body element.
document.body.appendChild(div);
So this is it for this article. Let us learn about how we can remove elements from the DOM in the next article.
PS - If you are looking to learn Web Development, I have curated a FREE course for you on my YouTube Channel, check the below article :
Looking to learn React.js with one Full Project, check this out :
👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev
23