Browsers parse the HTML document and construct the nodes based on the contents of the HTML file. All nodes are created by the browser for the initial load. However, it is possible to dynamically inject new nodes using the
tagName as mandatory argument. A
tagName can be any valid tag like
p etc. If tag name is not recognized by browser, it creates element of
Let’s see how this work
To create a
div element the
tagName is going to have a value of
div as follows
We have created an element however it will not be visible on the document as of now. To make the newly created element visible on the page we need to
To enter some content and append the new
element on-page, first, we need to get the reference of the element - let’s assign it to variable
Next, we create a text node to give it some content. To create text node we use another method i.e.
document.createTextNode which accepts text as an argument
To display text inside
div element, we need to append it to
div element using
appendChild method defined inside DOM Node interface
Finally, we can attach the
div element to the document body to make it visible on the screen
Inserting dynamic element inside existing element work very much similar to appending it to the body.
Let’s start with the following markup to insert the dynamic element inside the existing element
Next, we will append a paragraph element having text “50% off on the above items!!”
Let’s create paragraph element with above text inside it
Now, we need to get the handle of an element where we need to append the newly created paragraph element - I have given the target element an
parent so that we can easily access it. We will be using
document.querySelector() method to select the desired element.
So, once we have the handle of the parent element, we can use
appendChild to insert item(s) at last inside the target element.
document.createElement()creates a new HTML element.
document.createTextNode()creates a text node.
appendChild()method appends dynamic element to body or target element.
document.querySelector()allows to select desired element using any valid selector.