XML DOM setAttributeNode() method
Definition and Usage
The setAttributeNode() method adds a new attribute node.
If the element already has an attribute with the specified name, that attribute will be replaced by the new attribute. If the new attribute replaces an existing attribute, it will return the replaced attribute, otherwise it will return NULL.
Syntax:
elementNode.setAttributeNode(att_node)
Parameter | Description |
---|---|
att_node | Required. Specifies the attribute node to be set. |
Explanation
This method adds a new Attr node to the attribute collection of the Element node. If the current Element already has an attribute with the same name, this method will replace that attribute with the new one and return the replaced Attr node. If such an attribute does not exist, this method will define a new attribute for the Element.
Συνήθως, setAttribute() μέθοδοςείναι πιο απλό από το setAttributeNode()
Παράδειγμα
Σε όλες τις παραδείξεις, θα χρησιμοποιούμε αρχεία XML books.xmlκαι τις συνάρτησεις JavaScript loadXMLDoc()。
Η παρακάτω κώδικας προσθέτει την ιδιότητα "edition" σε όλα τα στοιχεία <book> στο "books.xml":
xmlDoc=loadXMLDoc("books_ns.xml");
x=xmlDoc.getElementsByTagName("book")[0];
ns="http://www.codew3c.com/edition/";
x.setAttributeNS(ns,"edition","first");
document.write(x.getAttributeNS(ns,"edition"));
Αποτελέσματα εξόδου:
first