Expressions like Element.getAttribute("id") and Element.id return the same thing.
Which one should be used when we need attributes of an HTMLElement object?
Is there any cross browser issue with these methods like getAttribute() and setAttribute()?
Or any impact on performance between directly accessing object properties vs using these attribute methods?
getAttributeretrieves the attribute of a DOM element, whileel.idretrieves 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.hrefandel.getAttribute('href')for an anchor element.For example:
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‘scheckedproperty. The DOM property returnstrueorfalsewhile 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
valueproperty of aninputelement. 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:
valueof aninputelement).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).