Skip to content
doubtly

2 answers

Best answer

<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>
Doubtly · 3 Apr 2022 Report
Was this answer helpful?

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:

  1. createElement("p") makes a new, empty <p> element in memory.
  2. createTextNode() makes the text, and appendChild() puts it inside the new paragraph. (You can also write newP.textContent = "...";.)
  3. getElementById("box").appendChild(newP) inserts the paragraph into the page as the last child of the div.

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?

Your answer

Log in or create a free account to answer this question.