Dynamic Title Adding Script

Interact with your page content live. This script demonstrates how to take user input from a form field and dynamically append it to the webpage structure (DOM) without triggering a server reload.

Live Content Editor

New text will appear here...

Copy the Script

<script>
function addText() {
  var newText = document.addForm.newTitle.value;
  if (newText != "") {
    var newElement = document.createElement("p");
    newElement.innerText = newText;
    document.getElementById("addLoc").appendChild(newElement);
    document.addForm.newTitle.value = ""; // Clear input
  } else {
    alert("Please enter some text first.");
  }
}
</script>

<form name="addForm">
  <input type="text" name="newTitle">
  <input type="button" value="Add Text" onClick="addText()">
</form>

<div id="addLoc"></div>

Frequently Asked Questions

Using DOM methods like createElement and innerText (or createTextNode) is generally safer against XSS attacks because it treats input as plain text. innerHTML parses HTML tags, which can be risky if user input is not sanitized.

Yes. In the script, you can access the style property of the new element. For example: newElement.style.color = "red"; or newElement.className = "my-custom-style";.

Yes, basic DOM manipulation methods like getElementById and appendChild are supported in very old browsers, including IE6.