Dom Change Nodes in XML
How to Change (Modify) Nodes in XML DOM
You can easily modify the content or attributes of existing XML nodes using the DOM API.
Ways to Change Nodes
Change the text content of an element.
Update or add attributes.
Replace or remove child nodes.
Example XML
<book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author></book>JavaScript Example to Modify Nodes
// Assume xmlDoc is your parsed XML document// Get the <book> elementconst book = xmlDoc.getElementsByTagName("book")[0];// Change attribute 'id'book.setAttribute("id", "202");// Change the <title> textconst title = book.getElementsByTagName("title")[0];title.textContent = "Effective Java - 3rd Edition";// Change the <author> textconst author = book.getElementsByTagName("author")[0];author.textContent = "Joshua Bloch and Others";Explanation
Use
setAttribute()to modify attributes or add new ones.Use
.textContentto change the text inside an element.
Full Example with Display
<!DOCTYPE html><html><head><title>DOM Change Nodes in XML</title></head><body><h2>Modify XML Nodes</h2><button onclick="changeNodes()">Change Book Info</button><pre id="xmlOutput"></pre><script>const xmlString = `<book id="101"> <title>Effective Java</title> <author>Joshua Bloch</author></book>`;const parser = new DOMParser();const xmlDoc = parser.parseFromString(xmlString, "text/xml");function displayXML() { const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(xmlDoc); document.getElementById("xmlOutput").textContent = xmlStr;}function changeNodes() { const book = xmlDoc.getElementsByTagName("book")[0]; // Change attribute book.setAttribute("id", "202"); // Change title text const title = book.getElementsByTagName("title")[0]; title.textContent = "Effective Java - 3rd Edition"; // Change author text const author = book.getElementsByTagName("author")[0]; author.textContent = "Joshua Bloch and Others"; displayXML();}displayXML();</script></body></html>Summary
| Operation | Method/Property |
|---|---|
| Change attribute | element.setAttribute(name, value) |
| Change element text | element.textContent = "new text" |
Want to learn how to remove nodes or replace nodes next?