JS: Get Element's Attribute Value
getAttribute method
The getAttribute
is generic, works in both HTML and XML.
node.getAttribute(AttributeName)
-
Return a node/element's attribute value. If the attribute doesn't exist, returns
null
. (browsers before 2010 may return empty string""
).
node
is a HTML element or XML node.
AttributeName
should be a string. e.g."class"
,"id"
, etc.// get first link const xx = document.getElementsByTagName("a")[0]; xx.getAttribute("href");
As of 2012-04-26, this works in all major browsers.
Get {Id, Clas, Href, Width} Attributes by Properties
If working in HTML (not XML), you can use a property directly for standard HTML attributes.
Example:
x = element.id
x = element.class
x = linkElement.href
x = imgElement.width
This
x.getAttribute("href")
is same as
x.href
When to use getAttribute or setAttribute instead of element properties?
If you work with XML, such as scripting SVG, or has non-standard attribute such as HTML5 Custom Data Attribute.
example:
SVG has attribute stroke
that does not have a DOM property.
γsee Practical SVG Tutorialγ
Example of creating a non-standard attribute:
x.setAttribute("data-user-name","John")
Class Attribute
When working with the attribute class
, there are more convenient methods.
See: JS: List, Add, Remove Class Attribute
Set Element's Attribute Value
JS: Set Element's Attribute Value