The HTML attribute is a special keyword which is used inside the opening tag of the element. The attribute is used to control the element's behaviour and to provide additional information to the element
The attribute is generally a name-value pair which is separated by
When the browsers load HTML and generate DOM object from it, then most standard HTML attributes automatically become properties of the DOM objects.
For example, if the tag is
<p title="paragraph title">, then the DOM object has
thisParagraph.title = "paragraph title".
Note: Every attribute of an element does not become DOM object property, only the standard attribute of the element becomes DOM object property.
From the above statement, you can easily understand that you can't access non-standard attributes since there won't be a DOM property for it.
So is there a way to access non-standard attributes?
The method returns a
boolean value, true if attribute exist in the element and false if attribute does not exist.
const result = element.hasAttribute(attributeName);
getAttribute() method is used to get the attribute value from any DOM element. This method returns the value of the attribute specified if the attribute doesn't exist then value returned is null or
"" (empty string).
const value = element.getAttribute(attributeName);
Here: 'attributeName'' is the name of the attribute and 'value' is the value of the attribute.
getAttribute method is called on HTML element, the method lower-cases its argument before proceeding.
setAttribute() method is used to set new attribute and its value to the DOM element. If the attribute already exists then the value of the attribute is updated with the new value.
This method takes 2 argument name and value. Here in the syntax: 'name' is the name of the attribute and 'value' is the value of the attribute.
Regardless of the actual value of Boolean attributes its presence make it to be true.
So while setting a boolean the attribute some people just pass attribute name, but it is a non-standard approach to do it. You should specify an empty string (
"") as a value.
Since value is converted to a string don't pass
null as a value because it will be converted to "null".
removeAttribute() method is used to remove the attribute with the specific name from the element.
const value = element.removeAttribute(attrName);
Here: 'attriName' is name of the attribute.