There are two different methods in JavaScript, using which you can easily add text or contents to a <div> element, dynamically.
Method 1: Add text to DIV using innerHTML Property
The innerHTML property will add new contents to a <div> element that is either empty or already has some content in it. For example,
<body> <p> <input type='button' onclick='fillData()' value='Fill Div with Data'> </p> <div id='container'> <p> Content inside p element. </p> </div> </body> <script> let fillData = () => { let ele = document.getElementById('container'); ele.innerHTML += 'Hello, I am Arun'; } </script> </html>
Using the innerHTML property, you to add text, markup and styles to the element, dynamically. It means, you can append tags like <b> or <span> etc. to the content.
For example, ele.innerHTML += '<b>Hello, I am Arun</b>';. The Hello... string has <b></b> tags within the quotes, to bold the string.
There’s another important thing, which is worth noting is the use of +=, immediately after ".innerHTML". This will allow you to add (in-fact append) new contents with existing contents or, elements that already exists inside the <div> element. See the above example, I already have a <p> element with some contents in it.
Method 2: Add text to DIV using appendChild() Method
You can also use the appendChild() method in JavaScript to add text or contents to a <div>. Its different from innerHTML property that I have explained in the first example (see above).
With innerHTML, you can directly provide texts, markups, style etc. to the element.
With "appendChild()", you have to create node (a text node here) for the parameter, to append the contents to the <div>.
See this example.
<body> <p> <input type='button' onclick='fillData()' value='Click to fill DIV with data'> </p> <div id='container'> <p> Content inside p element. </p> </div> </body> <script> let fillData = () => { let ele = document.getElementById('container'); let node = document.createTextNode ('Hello, I am Arun'); ele.appendChild(node); } </script> </html>
This too will serve the purpose. It will add text to a <div> element. However, using this method you can only add plain texts. You cannot add additional markups or style to the text.
Both the methods, that I have described above have its pros and cons. Use it judiciously, as both fits in different situations. Remember, if you are using innerHTML property to add extra or new content to an existing content, use “+=” after the property. Or else, it will remove all content along with elements (nodes etc.) and add completely new content the element.
ele.innerHTML = 'Hello, I am Arun'; // will add completely new content and remove previous content
ele.innerHTML += 'Hello, I am Arun'; // will add new content with existing content