revision:
The getAttributeNames() method of the Element interface returns the attribute names of the element as an Array of strings. If the element has no attributes it returns an empty array.
Using getAttributeNames() along with getAttribute(), is a memory-efficient and performant alternative to accessing Element.attributes.
The names returned by getAttributeNames() are qualified attribute names, meaning that attributes with a namespace prefix have their names returned with that namespace prefix (not the actual namespace), followed by a colon, followed by the attribute name (for example, xlink:href), while any attributes which have no namespace prefix have their names returned as-is (for example, href).
getAttributeNames()
Parameters: none
const element = document.createElement("a"); // set "href" attribute with no namespace and no namespace prefix element.setAttribute("href", "https://example.com"); // set "href" attribute with namespace and also "xlink" namespace prefix element.setAttributeNS( "http://www.w3.org/1999/xlink", "xlink:href", "https://example.com" ); // set "show" attribute with namespace but no namespace prefix element.setAttributeNS("http://www.w3.org/1999/xlink", "show", "new"); // Iterate over element's attributes for (const name of element.getAttributeNames()) { const value = element.getAttribute(name); console.log(name, value); } // logs: // href https://example.com // xlink:href https://example.com // show new
example: get attribute names.
<div> <p id="name-1"></p> <p id="name-2"></p> </div> <script> const element = document.createElement('a') element.setAttribute('href', 'https://example.com') element.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'https://example.com') element.setAttributeNS('http://www.w3.org/1999/xlink', 'show', 'new') for (let name of element.getAttributeNames()) { let value = element.getAttribute(name); console.log(name, value); document.getElementById("name-1").innerHTML += (name, value) + "<br>"; } </script>