Welcome to the XML DOM NamedNodeMap Object lesson! This tutorial is designed to help you understand and utilize the NamedNodeMap object in the context of XML document manipulation. Let's dive in!
The NamedNodeMap is an abstract collection of Attr objects in an XML document. Each attribute of an XML element has a corresponding Attr object in the NamedNodeMap. This object allows you to iterate through the attributes of an XML element.
Before we proceed, let's create a simple XML document for demonstration purposes.
<book>
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<year>1951</year>
</book>To access the NamedNodeMap for an XML element, we use the getAttributes() method. Let's examine our XML document.
const doc = new DOMParser().parseFromString(xml, "text/xml");
const book = doc.documentElement.firstChild;
console.log(book.attributes);In the above code, doc.documentElement.firstChild gets the <book> element, and attributes returns the NamedNodeMap for that element.
You can iterate through the attributes of an element using a simple for...of loop:
for (const attr of book.attributes) {
console.log(`${attr.name} = ${attr.value}`);
}This will output:
type = book
(The "type" attribute is not part of our XML document but is automatically added by the DOM parser.)
You can also add, remove, or modify attributes using the NamedNodeMap. Here's an example of adding a new attribute:
const newAttr = doc.createAttribute("publisher");
newAttr.value = "Little, Brown and Company";
book.attributes.setNamedItem(newAttr);After adding the new attribute, the NamedNodeMap of the <book> element will include the new publisher attribute.
What is the purpose of the NamedNodeMap object in the context of XML DOM?