Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does attribute node exist in HTML?

Can anyone give me an example of attribute node in HTML, whose nodeType value will be 2? Thanks in advance.

like image 386
Jennifer Massey Avatar asked May 02 '26 03:05

Jennifer Massey


2 Answers

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.

like image 197
Timothy Gu Avatar answered May 04 '26 16:05

Timothy Gu


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

like image 23
peterdotjs Avatar answered May 04 '26 16:05

peterdotjs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!