DOM Traversal and Manipulation

Estimated study time: 13 minutes.

Traversal means moving through the DOM tree — visiting parents, children, and siblings — while manipulation means changing what's there once you've found it.

Traversing the Tree

let root = xmlDoc.documentElement;
let firstChild = root.firstChild;
let next = firstChild.nextSibling;
let parent = firstChild.parentNode;

Every node exposes these relationships, letting you walk in any direction without needing to re-query the whole document.

Looping Through Children

let modules = xmlDoc.getElementsByTagName("module");
for (let i = 0; i < modules.length; i++) {
  console.log(modules[i].textContent);
}

Adding a New Element

let newModule = xmlDoc.createElement("module");
newModule.textContent = "Power BI Basics";
xmlDoc.getElementsByTagName("modules")[0].appendChild(newModule);

Removing an Element

let target = xmlDoc.getElementsByTagName("module")[0];
target.parentNode.removeChild(target);

Replacing an Element

let oldNode = xmlDoc.getElementsByTagName("module")[0];
let newNode = xmlDoc.createElement("module");
newNode.textContent = "Updated Module";
oldNode.parentNode.replaceChild(newNode, oldNode);
💡 Tip: When removing or replacing nodes while looping through a live node list, iterate over a copied array instead — live lists update in real time and can cause you to skip elements.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with the Data Analytics Course at Uncodemy.

Explore XML Course →