Querying Attr Nodes

DOM provides a way to represent both HTML and XML markup. Whereas HTML attribute values may be fully represented with strings, this is not so for XML attributes. For this reason, DOM provides an Attr
interface for representing attributes as nodes. Those are not part of the DOM tree. So, you will not bump into them while traversing the DOM.
For HTML markup, Attr nodes have a single Text node child that you may query by way of the value member. On the other hand, XML Attr nodes may contain both a Text and EntityReference
node, which is why XML attributes cannot be conveyed with just a string.

You can query the Attr node with Element.getAttributeNode(). So, append Node to Element.getAttribute(), and you’re good to go:

var myAttrNode = document.getElementById("twitter").getAttributeNode("class");

Now query some members from the Node interface. Remember to stop and click Run prior to each comment in order to verify the return value:

myAttrNode.nodeType;
// 11
myAttrNode.nodeName;
// "class"
myAttrNode.nodeValue;
// "sprite"
Now query some members the Attr node received by way of the Attr interface:
myAttrNode.name;
// "class"
myAttrNode.value;
// "sprite"
myAttrNode.value = "sprout";
myAttrNode.value;
// "sprout"
myAttrNode.specified;
// true

So for an Attr node, Node.nodeName and Attr.name contain the same value, a string indicating the name of the attribute. Similarly, both Node.nodeValue and Attr.value contain the value of the attribute
as a string. So, the first two members, name and value, are redundant. On the other hand, Attr.specified contains a boolean: true if you explicitly set the attribute in your markup or by JavaScript and false if
not. So, false means the attribute value is a default from the document’s DTD. With those things in mind, querying Attr.specified will likely be the only time you work with an attribute through the Attr
interface (as a node) rather than the Element interface (as a string).

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents