How to Create HTML Element in JavaScript
Creating elements using HTML is not the only way to do it, although most of the time we are creating elements directly in the Html document because of simplicity, it is possible to be also done with JavaScript. In this article, we will take a look at how we can create elements with JavaScript only, and we will see how the JavaScript is doing that under the hood.
The Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
JavaScript Create Element
Creating DOM elements using js, adding text to the new element and appending the child to the Html body is not a hard task, it can be done in just a couple of lines of code. Let's see in the next example:
var div = document.createElement('div'); //creating element
div.textContent = "Hello, World"; //adding text on the element
document.body.appendChild(div); //appending the element
In the example above, on the first line, we are creating new div with the method createElement()
which has been called on the document object. In the method, we are passing an argument telling which element we want to be created. On the second line, we are using the textContent
property to add text to our newly created element. Lastly, on the third line, we are using the document, body property to call the appendChild()
method and pass our element we want to append to the body, in our case the newly created div element.
So as we can see, the code above is equivalent to:
<body>
<div>Hello, World</div>
</body>
JavaScript Remove Element
Removing DOM elements is also simple and easy as creating DOM elements. Each DOM element has a property that’s the DOM element’s parent. To remove an element, we just need to call the removeChild()
method, and pass the child element we want to remove as an argument to the same method:
div.parentNode.removeChild(div);
As you can see it is even simpler than creating elements!.
Create Element with jQuery
As an alternative to vanilla JavaScript, we can use the jQuery library to do the same things as creating, adding, removing DOM elements, etc.
var div = $('<div/>').text("Hello, World").appendTo(document.body);
In the long run, using jQuery can be not the best thing because, with today's demand for modern technologies like React, vanilla JavaScript is a much better skillset.
Now I hope you can understand how does the creating, adding and removing of DOM elements works in JavaScript and jQuery. If you find this article helpful feel free to share it.
Tweet