JavaScript Introduction | Document Object Model | Manipulating Nodes
Changing Node Values
You can use the nodeValue property to change the value of a specific node.
The setAttribute() method also lets you change the value of an attribute node.
Text in Element Nodes
An element node does not directly hold a text value. The text of an element node is stored in a text node, which is a child node of that element. Therefore, when you want to check or change the text value of an element node, you must access the text node contained inside it.
You can change the value of a text node with the nodeValue property.
var para = document.getElementById("text"); // Selects the element whose ID is "text".
function changeText() {
para.firstChild.nodeValue = "Text changed!";
}
Changing Attribute Node Values
You can change the value of an attribute node with both the nodeValue property and the setAttribute() method.
If the attribute whose value you want to change does not exist, setAttribute() first creates that attribute and then sets its value.
var para;
function changeAttribute() {
// Sets the class attribute of the first <p> element to "para".
document.getElementsByTagName("p")[0].setAttribute("class", "para");
// Once the class is set, the style defined for that class is applied automatically.
}
Replacing Element Nodes
You can use the replaceChild() method to replace an existing element node with a new element node.
The syntax of the replaceChild() method is as follows.
Syntax
replacedNode = parentNode.replaceChild(newChildNode, oldChildNode);
- New child node: Pass the element node to add to the child node list.
- Old child node: Pass the element node to remove from the child node list.
The following example removes the first child node and inserts the third element in its place.
var parent = document.getElementById("parent"); // Selects the parent node.
var first = document.getElementById("first");
var third = document.getElementById("third");
function changeNode() {
parent.replaceChild(third, first); // Removes first and inserts third in its place.
}
Replacing Text Node Data
You can use the replaceData() method to replace the text data of a text node.
The syntax of the replaceData() method is as follows.
Syntax
textNode.replaceData(offset, count, newData);
- Offset: The offset starts at 0 and specifies the character position in the existing text data where replacement begins.
- Number of characters to replace: Pass the total number of characters to replace from the existing text node data.
- New data: Pass the text data to insert.
var text = document.getElementById("text").firstChild; // Selects the text node of the element whose ID is "text".
function changeText() {
text.replaceData(7, 4, "7 PM"); // Replaces four characters from the seventh character of the text node with "7 PM".
}