

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a new element to HTML DOM in JavaScript?
To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element.
Steps to follow
1) First, create a div section and add some text to it using <p> tags.
2) Create an element <p> using document.createElement("p").
3) Create a text, using document.createTextNode(), so as to insert it in the above-created element("p").
4) Using appendChild() try to append the created element, along with text, to the existing div tag.
Thus a new element is created(<p>) and appended to the existing element(<div>).
Example
In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output.
<html> <body> <div id="new"> <p id="p1">Tutorix</p> <p id="p2">Tutorialspoint</p> </div> <script> var tag = document.createElement("p"); var text = document.createTextNode("Tutorix is the best e-learning platform"); tag.appendChild(text); var element = document.getElementById("new"); element.appendChild(tag); </script> </body> </html>
Output
Tutorix Tutorialspoint Tutorix is the best e-learning platform
- Related Questions & Answers
- How to add a class to DOM element in JavaScript?
- How to add an event handler to an element in JavaScript HTML DOM?
- How to add many Event Handlers to the same element with JavaScript HTML DOM?
- Add oninput attribute to HTML element with JavaScript?
- How to add a new element in the XML using PowerShell?
- How to add a new value to each element of list in R?
- How to add an address element in HTML?
- How to add an element to a javascript object?
- Remove and add new HTML Tags with JavaScript?
- How to add rows to a table using JavaScript DOM?
- How to add two arrays into a new array in JavaScript?
- MongoDB query to add new array element in document
- How to add a unique id for an element in HTML?
- How to add new value to an existing array in JavaScript?
- How to add a new list element under a <ul> using jQuery?
Advertisements