getAttribute() versus Element object properties?
getAttribute
retrieves the attribute of a DOM element, while el.id
retrieves the property of this DOM element. They are not the same.
Most of the time, DOM properties are synchronized with attributes.
However, the synchronization does not guarantee the same value. A classic example is between el.href
and el.getAttribute('href')
for an anchor element.
For example:
<a href="/" id="hey"></a>
<script>
var a = document.getElementById('hey')
a.getAttribute('href') // "/"
a.href // Full URL except for IE that keeps '/'
</script>
This behavior happens because according to the W3C, the href property must be a well-formed link. Most browsers respect this standard (guess who doesn't?).
There is another case for the input
's checked
property. The DOM property returns true
or false
while the attribute returns the string "checked"
or an empty string.
And then, there are some properties that are synchronized one-way only. The best example is the value
property of an input
element. Changing its value through the DOM property will not change the attribute (edit: check the first comment for more precision).
Because of these reasons, I'd suggest you keep using the DOM properties, and not the attributes, as their behavior differs between the browsers.
In reality, there are only two cases where you need to use the attributes:
- A custom HTML attribute, because it is not synced to a DOM property.
- To access a built-in HTML attribute, which is not synced from the property, and you are sure you need the attribute (for example, the original
value
of aninput
element).
If you want a more detailed explaination, I strongly suggest you read this page. It will take you a few minutes only, but you will be delighted by the information (which I summed up here).
Difference between Element.value and Element.getAttribute(value)
The difference is that element.value
is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.
While getAttribute('value')
will still show the original value="whateverWasHere"
value.
jsFiddle DEMO
difference between JS get element's attribute with elem.getAttribute(attr) and elem[attr]
I have an answer. It handles tagName
specially. It's not great. But it can get the job done.
var value = elem.getAttribute(attr);
if (!value) {
if (attr == "tagName") {
value = elem["tagName"] || "";
} else {
value = "";
}
}
return value;
JavaScript Element.value vs Element.getAttribute(value)
The difference is that element.value
is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.
While getAttribute('value')
will still show the original value="whateverWasHere"
value.
jsFiddle DEMO
Difference between object.src and object.getAttribute('src')
You can see the difference in the HTML specification as “permitted attributes” versus “DOM interface”.
The specific difference for URLs is described in Reflecting content attributes in IDL attributes:
If a reflecting IDL attribute is a
DOMString
attribute whose content attribute is defined to contain a URL, then on getting, the IDL attribute must resolve the value of the content attribute relative to the element and return the resulting absolute URL if that was successful, or the empty string otherwise; and on setting, must set the content attribute to the specified literal value. If the content attribute is absent, the IDL attribute must return the default value, if the content attribute has one, or else the empty string.
What is the difference between properties and attributes in HTML?
When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
For instance, this HTML element:
<input type="text" value="Name:">
has 2 attributes (type
and value
).
Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.
For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes
property of that object.
When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:
<input id="the-input" type="text" value="Name:">
the corresponding DOM node will have id
,type
, and value
properties (among others):
The
id
property is a reflected property for theid
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value.id
is a pure reflected property, it doesn't modify or limit the value.The
type
property is a reflected property for thetype
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value.type
isn't a pure reflected property because it's limited to known values (e.g., the valid types of an input). If you had<input type="foo">
, thentheInput.getAttribute("type")
gives you"foo"
buttheInput.type
gives you"text"
.In contrast, the
value
property doesn't reflect thevalue
attribute. Instead, it's the current value of the input. When the user manually changes the value of the input box, thevalue
property will reflect this change. So if the user inputs"John"
into the input box, then:theInput.value // returns "John"
whereas:
theInput.getAttribute('value') // returns "Name:"
The
value
property reflects the current text-content inside the input box, whereas thevalue
attribute contains the initial text-content of thevalue
attribute from the HTML source code.So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the
defaultValue
property, which is a pure reflection of thevalue
attribute:theInput.value // returns "John"
theInput.getAttribute('value') // returns "Name:"
theInput.defaultValue // returns "Name:"
There are several properties that directly reflect their attribute (rel
, id
), some are direct reflections with slightly-different names (htmlFor
reflects the for
attribute, className
reflects the class
attribute), many that reflect their attribute but with restrictions/modifications (src
, href
, disabled
, multiple
), and so on. The spec covers the various kinds of reflection.
javascript dom, how to handle special properties as versus attributes?
Except for rare special cases listed below, always use the property. Once the browser has parsed the intial HTML, attributes are no help to you unless you're serializing the DOM back to HTML for some reason.
Reasons to always favour properties:
- dealing with properties is simpler (see Boolean properties such as
checked
: just usetrue
andfalse
and never worry whether you should be removing the attribute, or setting it to""
or"checked"
) - not every property maps to an attribute of the same name. For example, the
checked
property of a checkbox or radio button does not correspond to any attribute; thechecked
attribute corresponds to thedefaultChecked
property and does not change when the user interacts with the element (except in old IE; see next point). Likewisevalue
anddefaultValue
. setAttribute()
andgetAttribute()
are broken in older versions of IE.
Special cases:
- Attributes of
<form>
elements. Since each form input is mapped to a property of its parent<form>
element corresponding to itsname
, it's safer to usesetAttribute()
andgetAttribute()
to obtain properties of the form such asaction
,name
andmethod
. - Custom attributes, e.g.
<p myspecialinfo="cabbage">
. These will not generally create equivalent properties on the DOM element object, sosetAttribute()
andgetAttribute()
should be used.
One final consideration is that there is not an exact correspondence between attribute and property names. For example, the property equivalent of the class
attribute is className
, and the property for the for
attribute is htmlFor
.
object.className or object.getAttribute(className/class)?
getAttribute("class")
is more universal, because it can be used in different types of documents. In XML documents, most importantly. Including SVG.
element.className
works only in HTML. It is described in the DOM level 2 HTML specs.
Related Topics
Redirect Parent Window from an Iframe Action
Expression Inside Switch Case Statement
How to Use Window.Postmessage Across Domains
Bootstrap 4 Navbar Not Collapsing on Large Screen
Google Maps API V3: Infowindow Not Sizing Correctly
How to Iterate Through All Attributes in an HTML Element
HTML Anchor Link - Href and Onclick Both
Get the Text Content from a Contenteditable Div Through JavaScript
Determine Original Size of Image Cross Browser
Filter Array of Objects with Another Array of Objects
How to Access an SQLite Database from JavaScript
How to Do a Horizontal Scroll on Mouse Wheel Scroll
Loading an Image to a <Img> from <Input File>