XML — DOM
What is DOM?
DOM (Document Object Model) is a programming interface for XML/HTML documents.
Loading XML in JavaScript
var parser = new DOMParser();
var xmlString = '<book><title>My Book</title></book>';
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
Accessing Elements
var title = xmlDoc.getElementsByTagName("title")[0];
console.log(title.childNodes[0].nodeValue);
Creating Elements
var newElement = xmlDoc.createElement("price");
var textNode = xmlDoc.createTextNode("29.99");
newElement.appendChild(textNode);
xmlDoc.getElementsByTagName("book")[0].appendChild(newElement);
Modifying Elements
var title = xmlDoc.getElementsByTagName("title")[0];
title.childNodes[0].nodeValue = "New Title";
Removing Elements
var book = xmlDoc.getElementsByTagName("book")[0];
book.removeChild(xmlDoc.getElementsByTagName("price")[0]);
Attributes
var book = xmlDoc.getElementsByTagName("book")[0];
book.setAttribute("genre", "fiction");
var genre = book.getAttribute("genre");
DOM Methods Summary
| Method | Description |
|---|---|
| getElementsByTagName() | Get elements by tag |
| getElementsByClassName() | Get elements by class |
| getElementById() | Get element by ID |
| createElement() | Create new element |
| createTextNode() | Create text node |
| appendChild() | Add child |
| removeChild() | Remove child |
| setAttribute() | Set attribute |
| getAttribute() | Get attribute |
Mini Practice
- Load XML from a string
- Access and modify elements
- Create and add new elements
- Set and get attributes
Up Next
Continue with XPath — navigating XML documents with XPath.
Related Topics
Frequently Asked Questions about DOM
What is DOM in XML?
DOM is a fundamental concept in XML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn DOM?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn DOM.
Why is DOM important in XML?
DOM is essential for XML development. Understanding this concept will help you write better code and solve real-world problems more effectively.