How to Add HTML Elements into DOM through JavaScript Code
We all might have encountered the case where we need to insert the HTML elements through JavaScript code as part of some event handling. This is called as dynamic addition of UI Controls from the code.
Significance of DOM(Document Object Model)
In JavaScript world its relatively easy to add any html control to the DOM (Document Object Model). For the control to be visible in the UI it has to be added to the DOM.
We will see now an example of how this can be done. This requires some basic understanding of the HTML and the JavaScript.
Lets see the existing HTML DOM structure where we would try to insert a custom element.
As shown above we have a div block which is labelled as "chat-messages". We will try to insert the custom html code into this block as shown in the figure below:
As shown in the figure above we have defined a function showMessagesInChat whose responsibility is to insert HTML code into the chat-messages div block.
In the first line of the JavaScript code we have created a div element using the API document.createElement(<Name of the Element>). Then add a class name to the added div block which is labelled as message in this case.
Then the main portion is to define the html code which would reside inside the div block. Here we can write our own HTML code and assign it to the innerHTML property of the div block. To allow for multiple lines in the HTML code we can use the operator `.
We can also embed dynamic values in this html code with the use of $ operator.
Finally once we are done with the html code we can add it to the DOM structure as shown in the last line of the function. It retrieves the DOM structure and finds the element provided as a parameter to the querySelector API and call appendChild passing inn the element we want to insert to the DOM.
Comments
Post a Comment