Adding-Replacing DOM Content
You can perform text changes either via the replaceChild( ) method or by assigning new text to a text node’s nodeValue property.The second way is a simpler approach for replacing text nodes.All it requires is a reference to the text node being replaced. You can assign that node’s nodeValue property its new string value:
document.getElementById(”parag2″).childNodes[0].nodeValue = “first”;
Code:
<html>
<head>
<title>Adding-replacing dom content</title>
<script type="text/javascript">
function modify()
{
var newElem = document.createElement("p");
newElem.id = "newP";
var newText = document.createTextNode("This is the second paragraph.");
newElem.appendChild(newText);
document.body.appendChild(newElem);
document.getElementById("parag2").childNodes[0].nodeValue = "first";
}
</script>
</head>
<body>
<button onclick="modify()">Add-Replace text</button>
<p id="parag1">This is the <span id="parag2">one</span> paragraph on the page.</p> </body> </html>
When an element’s content is entirely text this is the most streamlined way to swap text on the fly using the W3C DOM syntax.
Leave a Reply
You must be logged in to post a comment.
