Add HTML elements dynamically

HTML documents can be easily accessed and manipulated using HTML DOM , which represents an HTML document as a tree-structure. When an HTML document is loaded in a browser window, it becomes a Document object. With document.createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document. example
<html> <body> <button onclick="create()">Create Heading</button> <script> function create() { var h1 = document.createElement('h1'); h1.textContent = "New Heading!!!"; h1.setAttribute('class', 'note'); document.body.appendChild(h1); } </script> </body> </html>
So document.createElement is used with an HTML tag to create the element. The textContent is then modified and then the class attribute is modified using setAttribute . This could also be used to add a data attribute or any other kind of attribute, like you can in HTML. Finally the element is appended to the body using the body element's appendChild method. Actually, It's essentially equivalent to < H1 class="note" > New Heading!!! < /h1 > . The power of what we seen today is that we are creating and styling elements "on the fly". It's your decision to either add all the elements on the page while designing or you can create and insert HTML elements at runtime, that is dynamically using the createElement() method.