TExcelTAD
Home › XML › DOM Add Nodes

XML DOM Add Nodes

Once you have created a node, you place it in the tree. Where it goes — at the end, at the start, before a particular sibling — depends on the method you choose.

Insertion methods

Method Inserts Accepts strings?
parent.appendChild(node) As the last child No
parent.insertBefore(node, ref) Before child ref (null = at the end) No
parent.append(...nodes) As the last children Yes
parent.prepend(...nodes) As the first children Yes
ref.before(...nodes) / ref.after(...nodes) Next to ref, as siblings Yes
el.insertAdjacentElement(pos, node) beforebegin, afterbegin, beforeend, afterend No

appendChild and insertBefore are the classic W3C methods supported everywhere; append, prepend, before and after are newer, shorter and accept several nodes at once.

Adding at the end, start and middle

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xmlDoc = new DOMParser().parseFromString(
      '<queue><task>B</task><task>D</task></queue>', 'application/xml');
    const queue = xmlDoc.documentElement;
    const task = (t) => { const e = xmlDoc.createElement('task'); e.textContent = t; return e; };
    const show = (label) => console.log(label.padEnd(14), [...queue.children].map(c => c.textContent).join(' '));

    show('start:');
    queue.appendChild(task('E'));                 show('appendChild E:');
    queue.prepend(task('A'));                     show('prepend A:');
    const d = [...queue.children].find(c => c.textContent === 'D');
    queue.insertBefore(task('C'), d);             show('insert C:');
    d.after(task('D2'));                          show('after D:');
  </script>
</body>
</html>

Adding attributes

Attributes aren't children, so you "add" them with setAttribute (or setAttributeNode with a node from createAttribute):

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

    // Simple way
    xmlDoc.querySelector('[id="b1"]').setAttribute('rating', '5');

    // Attribute-node way
    const attr = xmlDoc.createAttribute('rating');
    attr.value = '4';
    xmlDoc.querySelector('[id="b2"]').setAttributeNode(attr);

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

Adding text to existing text

appendData() and insertData() modify a text node in place; append('…') adds a new text node. Either way the element's textContent grows:

js
const title = xmlDoc.querySelector('title');
title.firstChild.appendData(' (illustrated)');
// or: title.append(' (illustrated)');

Inserting moves existing nodes

If the node you insert is already in the document, it is moved, not copied. This makes reordering easy — here we sort books by year by re-appending them in order:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<library>
  <book><title>A Brief History of Time</title><year>1988</year></book>
  <book><title>The Hobbit</title><year>1937</year></book>
  <book><title>Cien años de soledad</title><year>1967</year></book>
</library>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
    const lib = xmlDoc.documentElement;

    const books = [...lib.querySelectorAll('book')]
      .sort((a, b) => a.querySelector('year').textContent - b.querySelector('year').textContent);
    lib.replaceChildren(...books);   // removes everything (incl. whitespace) and re-adds in order

    for (const b of lib.children) console.log(b.querySelector('year').textContent, b.querySelector('title').textContent);
    console.log('Still', lib.children.length, 'books — nothing was duplicated');
  </script>
</body>
</html>

To insert a copy instead, clone the node first — that's the next lesson.

Building a document from data

A typical job: turn a JavaScript array into XML.

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const orders = [
      { id: 101, customer: 'Mei', items: [['Pen', 3], ['Notebook', 1]] },
      { id: 102, customer: 'Olu', items: [['Stapler', 1]] },
    ];

    const xmlDoc = document.implementation.createDocument(null, 'orders');
    for (const o of orders) {
      const order = xmlDoc.createElement('order');
      order.setAttribute('id', o.id);
      const cust = xmlDoc.createElement('customer');
      cust.textContent = o.customer;
      order.appendChild(cust);
      for (const [name, qty] of o.items) {
        const item = xmlDoc.createElement('item');
        item.setAttribute('qty', qty);
        item.textContent = name;
        order.appendChild(item);
      }
      xmlDoc.documentElement.appendChild(order);
    }
    console.log(new XMLSerializer().serializeToString(xmlDoc));
  </script>
</body>
</html>

Tip: A node can be inserted into a different document only after adopting or importing it: xmlDoc.importNode(node, true) returns a copy owned by xmlDoc. Modern browsers adopt automatically on insertion, but importNode makes your intent clear.

Test yourself

Where does parent.insertBefore(newNode, null) put the node?

  1. At the beginning
  2. At the end
  3. Nowhere — it throws
  4. Before the parent

What happens if you appendChild a node that is already elsewhere in the same document?

  1. A copy is added
  2. It is moved to the new position
  3. An error is thrown
  4. Nothing happens

Which method adds nodes as the **first** children?

  1. append()
  2. prepend()
  3. after()
  4. appendChild()