Replace the text for a paragraph in JavaScript

Description

The following code shows how to replace the text for a paragraph.

Example


<!--from  w  w  w.j a va2  s.co  m-->

<!DOCTYPE HTML>
<html>
<body>
<p id="textblock">
This is a test.
</p>
<button id="pressme">Press Me</button>
<script>

var elem = document.getElementById("textblock");
document.getElementById("pressme").onclick = function() {
var textElem = elem.firstChild;
document.writeln("The element has " + textElem.length + " chars");
textElem.replaceWholeText("This is a new string ");
};
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Replace the text for a paragraph in JavaScript
Home »
  Javascript Tutorial »
    DOM »
      Update
Javascript Tutorial Update
Add and set new attribute for new created H...
Change attribute value for a HTML element i...
Replace a node in JavaScript
Replace the last child in JavaScript
Replace the text for a paragraph in JavaScr...
Set the inner text for a HTML element in Ja...
Set the outer html for a HTML element in Ja...
Update child element recursively in JavaScr...
Update the inner html for a HTML element in...
Use element's inner html to show the result...