node.attributes JavaScript
- 2022-08-22 fix the
node.attributes
, JavaScript: Element Attribute Methods
-
node.attributes
-
Get all attributes. Return a
Live Object
of
NamedNodeMap
object.const xattrs = document.getElementById("qgVv4").attributes; // get value of the id attribute console.log(xattrs["id"].value === "qgVv4"); // get value of the class attribute console.log(xattrs["class"].value === "c1 c2"); // get value of the data-x attribute console.log(xattrs["data-x"].value === "x1 x2");
<div id="qgVv4" class="c1 c2" x="x1 x2"></div>
// show that result is NamedNodeMap type const xattrs = document.getElementById("qgVv4").attributes; console.log( Reflect.apply(Object.prototype.toString, xattrs, []) === "[object NamedNodeMap]", );
NamedNodeMap
object is Array-Like Object and Iterable Object// show that NamedNodeMap is iterable const xattrs = document.getElementById("qgVv4").attributes; console.log( Reflect.has(xattrs, Symbol.iterator), );
// show own keys of NamedNodeMap const xattrs = document.getElementById("qgVv4").attributes; console.log( Reflect.ownKeys(xattrs), ); // [ "0", "1", "2", "id", "class", "data-x" ]
Each item of
NamedNodeMap
is a object.const xattrs = document.getElementById("qgVv4").attributes; for (let k of xattrs) console.log(typeof k === "object");
each object in NamedNodeMap is a Attr object
// each object in NamedNodeMap is a Attr object const xattrs = document.getElementById("qgVv4").attributes; for (let k of xattrs) { console.log( Reflect.apply(Object.prototype.toString, k, []) === "[object Attr]", ); }
type of Attr object is object:
// type of Attr object is object const xattr = document.getElementById("qgVv4").attributes[0]; console.log(typeof xattr === "object");
the Attr object is not a iterable, has no keys:
const xattr = document.getElementById("qgVv4").attributes[0]; // the Attr object is not a iterable console.log( Reflect.has(xattr, Symbol.iterator) === false, ); // no keys Reflect.ownKeys(xattr).length === 0;