const el = document.getElementById("card"); // id + class + data-id
if (el.hasAttributes()) {
console.log(el.getAttributeNames());
} else {
console.log([]);
}
List names.getAttributeNames() returns a string array.
Or use attributes. MDN points at el.attributes (NamedNodeMap).
Empty case. Bare elements → false / skip listing.
Example 3 — vs hasAttribute / length
Any-attributes vs one name vs counting with attributes.length.
JavaScript
const el = document.getElementById("card"); // class="box" (no data-role)
console.log(el.hasAttributes()); // true if any attrs
console.log(el.attributes.length > 0); // same idea
console.log(el.hasAttribute("data-role")); // one specific name
hasAttribute(name). Answers a different question — one name.
Pick the readable API. Prefer hasAttributes() for the “any?” check.
Compatibility
Browser Support
Element.hasAttributes() is Baseline Widely available (MDN: across browsers since July 2015). Safe for modern teaching and production code.
✓ Baseline · Widely available
hasAttributes()
Return true or false depending on whether the element has any attributes.
WideBaseline
Google ChromeFull support
Supported
Mozilla FirefoxFull support
Supported
Apple SafariFull support
Supported
Microsoft EdgeFull support
Supported
OperaFull support
Supported
Internet Explorer8+
Supported
hasAttributes()Widely available
Bottom line: Use hasAttributes as a clear guard before iterating attributes or listing names.
Frequently Asked Questions
It returns a boolean indicating whether the current element has any attributes at all (MDN). It does not check a specific attribute name.
No. MDN marks Element.hasAttributes() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
No. MDN lists no parameters. Call it as element.hasAttributes().
hasAttributes() checks if the element has any attributes. hasAttribute(name) checks one specific attribute by name.
hasAttributes() is true when attributes.length > 0. The method reads more clearly; length is equivalent for a quick count check.
MDN example: use element.attributes or getAttributeNames() to inspect individual attribute names and values.