JS DOM: Get Attribute
getAttribute method
The getAttribute
is generic, works in both HTML and XML.
node.getAttribute(AttributeName)
-
- Return a node's attribute value. If the attribute doesn't exist, return null. (browsers before 2010 may return empty string).
node
is a HTML element or XML node.AttributeName
should be a string.
// get first link const xx = document.getElementsByTagName("a")[0]; xx.getAttribute("href");
As of 2012-04-26, this works in all major browsers.
Get Attributes by Properties
some common HTML attributes are also available as properties.
element.id
element.class
linkElement.href
imgElement.width
When to Use GetAttribute or SetAttribute Instead of Element Properties
GetAttribute
and SetAttribute
are universal, always works.
Use Element Properties only for common elements that are HTML.
Do not use Element Properties when working with
- XML
- SVG
or if you have HTML: Custom Data Attribute
Class Attribute
When working with the attribute class
, there are more convenient methods.