TExcelTAD
Home › XML › DOM Change Nodes

XML DOM Change Nodes

A parsed XML document is not read-only. You can change text, add or update attributes, and rename the data in memory — then serialise the result back to XML (see the Serializing lesson). This lesson covers changing values; the following lessons cover removing, replacing, creating and adding whole nodes.

Changing element text

Assigning to textContent replaces all children of the element with a single text node:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<book id="b1"><title>The Hobit</title><price>8.99</price></book>', 'application/xml');

    xmlDoc.querySelector('title').textContent = 'The Hobbit';   // fix the typo
    const price = xmlDoc.querySelector('price');
    price.textContent = (Number(price.textContent) * 0.9).toFixed(2);   // 10% off

    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Special characters are escaped automatically when the document is serialised, so title.textContent = 'Tom & Jerry' is completely safe.

You can also change a text node directly through nodeValue (or data) — useful when an element has mixed content and you only want to touch one piece:

js
const blurb = xmlDoc.querySelector('blurb');   // <blurb>A <em>reluctant</em> hero</blurb>
blurb.firstChild.nodeValue = 'An ';            // only the first text node changes

Changing attributes

Method Effect
setAttribute(name, value) Creates the attribute or overwrites its value
getAttributeNode(name).value = v Changes an existing attribute node
toggleAttribute(name) Adds an empty attribute if missing, removes it if present
setAttributeNS(uri, 'prefix:name', v) Namespaced attribute
html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<library>
  <book id="b1" genre="fantasy"><title>The Hobbit</title></book>
  <book id="b2" genre="science"><title>A Brief History of Time</title></book>
  <book id="b3" genre="fantasy"><title>Cien años de soledad</title></book>
</library>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');

    // Rename a genre value everywhere
    for (const b of xmlDoc.querySelectorAll('book[genre="fantasy"]')) b.setAttribute('genre', 'fiction');
    // Add a new attribute to every book
    xmlDoc.querySelectorAll('book').forEach((b, i) => b.setAttribute('shelf', String.fromCharCode(65 + i)));
    // Change through the attribute node
    xmlDoc.querySelector('[id="b2"]').getAttributeNode('genre').value = 'popular-science';

    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Note: Attribute values are always strings. setAttribute('pages', 310) stores "310".

Changing many values at once

Combine selection and modification to apply rules across a document — like an "update" in a database:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<stock>
  <item sku="A1" qty="0"><name>Desk lamp</name><status>available</status></item>
  <item sku="B7" qty="12"><name>Bookend</name><status>available</status></item>
  <item sku="C3" qty="0"><name>Wall clock</name><status>available</status></item>
</stock>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');

    let changed = 0;
    for (const item of xmlDoc.querySelectorAll('item')) {
      if (Number(item.getAttribute('qty')) === 0) {
        item.querySelector('status').textContent = 'sold out';
        changed++;
      }
    }
    console.log(`Updated ${changed} items`);
    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Renaming an element?

There is no rename method — tagName is read-only. To rename, create a new element with the new name, move the children and attributes across, and replace the old one. The Replace Nodes lesson shows how.

Changes stay in memory

All of this happens on the in-memory DOM only. Nothing is written back to the original file or server. To keep the changes, serialise the document and save or upload the text (for example with fetch(url, { method: 'PUT', body: xmlText })).

Test yourself

What happens to the children of <p> when you set p.textContent = 'Hi'?

  1. They are kept and 'Hi' is appended
  2. They are all replaced by a single text node 'Hi'
  3. Only the first child changes
  4. Nothing — textContent is read-only

Which method adds a new attribute or overwrites an existing one?

  1. addAttribute()
  2. setAttribute()
  3. createAttribute()
  4. changeAttribute()