According to the docs, get_attribute actually returns the property rather than the attribute, unless the property doesn't exist, in which case it falls back to the attribute.
get_property will always return the property.
Is there a way to always get the attribute? I find it weird that a function named "get_attribute" would prioritize the property value over the attribute value.
get_attribute(attribute_name)
get_attribute(attribute_name) gets the given
attribute
orproperty
of the element.This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the
attribute
with the same name. If there’s noattribute
with that name,None
is returned.Values which are considered truthy, that is equals
true
orfalse
, are returned as booleans. All other non-None
values are returned as strings. For attributes or properties which do not exist,None
is returned.Args:
Example:
get_property(property_name)
get_property(property_name) gets the given property of the element.
Args:
Example:
Still sounds similar? Read below ...
Attributes and properties
When the browser loads the page, it parses the HTML and generates DOM objects from it. For element nodes, most standard HTML attributes automatically become properties of DOM objects.
For instance, if the tag is:
then the DOM object has
body.id="page"
.HTML attributes
In HTML, tags may have attributes. When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes and creates DOM properties from them.
So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard.
So, if an attribute is non-standard, there won’t be a DOM-property for it. In that case all attributes are accessible by using the following methods:
elem.hasAttribute(name)
: checks for existence.elem.getAttribute(name)
: gets the value.elem.setAttribute(name, value)
: sets the value.elem.removeAttribute(name)
: removes the attribute.An example of reading a non-standard property:
Property-attribute synchronization
When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa. But there are exclusions, for instance
input.value
synchronizes only fromattribute
-> toproperty
, but not back. This feature actually comes in handy, because the user may modify value, and then after it, if we want to recover the "original" value from HTML, it’s in the attribute.