Reputation: 173
Can anyone give me an example of attribute node in HTML, whose nodeType
value will be 2? Thanks in advance.
Upvotes: 3
Views: 449
Reputation: 3865
All attribute nodes must have a type of 2, as that is what document.ATTRIBUTE_NODE
is defined to.
See MDN documentation on Attr
type:
nodeType
This property now always returns 2 (ATTRIBUTE_NODE
).
Generalized example:
var attr = document.getElementById('tistheid').attributes[1]
document.getElementById('num').innerHTML = document.ATTRIBUTE_NODE
var output = document.getElementById('output')
output.innerHTML = 'constructor:\t' + attr.constructor.name
+ '\n' + 'type:\t' + attr.nodeType
+ '\n' + 'value:\t' + attr.value
<p id="tistheid" class="tistheclass"></p>
<p>
This is the value of ATTRIBUTE_NODE: <span id="num"></span>
</p>
<pre id="output">
</pre>
Despite an attempt by browser vendors and standardization organizations to make Attr
no longer inherit from Node
in the past, they eventually decided to keep Node
in the Attr
inheritance chain, due to compatibility concerns with older websites. However, as a developer now one should avoid using methods inherited from Node
on an Attr
.
Edit (2017-08-09): WHATWG has made Attr
inherit from Node
again. Update accordingly.
Upvotes: 6
Reputation: 1556
You can get a node of nodeType
value of 2 with Element.getAttributeNode()
Per: https://developer.mozilla.org/en-US/docs/Web/API/Attr
This type represents a DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types.
This type also appears to be deprecated per: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
Upvotes: 2
Reputation: 21
See Below
<!DOCTYPE html>
<html>
<body>
<p id="myP" class="buttonClass">Click the button to get the node type of this element.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myP").getAttributeNode("class").nodeType;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Upvotes: 0