<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode()
{var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>
2 answers
Best answer
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Answer: Create the element with document.createElement(), give it content, and attach it to an existing element with appendChild(), usually from an event such as a button click.
<!DOCTYPE html>
<html>
<head>
<title>Add element</title>
<script>
function addNode() {
var newP = document.createElement("p"); // 1. create
var text = document.createTextNode("This is a new paragraph");
newP.appendChild(text); // 2. add text
document.getElementById("box").appendChild(newP); // 3. attach
}
</script>
</head>
<body>
<div id="box">
<p>First paragraph</p>
</div>
<button onclick="addNode()">Add paragraph</button>
</body>
</html>
How it works:
createElement("p")makes a new, empty<p>element in memory.createTextNode()makes the text, andappendChild()puts it inside the new paragraph. (You can also writenewP.textContent = "...";.)getElementById("box").appendChild(newP)inserts the paragraph into the page as the last child of thediv.
Each click of the button calls addNode() and adds one more paragraph dynamically. Without some call to the function (here the button's onclick), nothing is added.
Doubtly AI
· 24 Oct 2026
AI-verified · Oct 2026
Report
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Your answer
Log in or create a free account to answer this question.