custom attribute works only with element.getAttribute("attribute") but not "element.attribute"

15,659

Only certain standard attributes are directly mapped to properties. This is not the defined behavior for non-standard (custom) attributes.

The forward compatible way of using custom attributes is to prefix them with data-.

<input ... data-custom_attr="custom_attr_text" ... />

Then they become available in HTML5 compliant browsers as:

element.dataset.custom_attr

But in legacy browsers, you'll still need to use .getAttribute().

Share:
15,659
Isti115
Author by

Isti115

Updated on July 24, 2022

Comments

  • Isti115
    Isti115 almost 2 years

    I have just noticed, that if I give a custom attribute to an html element, for example:

    <input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />
    

    then i can retrieve it like this:

    document.getElementById("my_button").getAttribute("custom_attr");
    

    and it will return "custom_attr_text", but if I do

    document.getElementById("my_button").custom_attr;
    

    then it returns undefined!

    I also noticed that with a built in attribute (for example value or id) both of the above works fine! Could somebody please explain why is this happening?

  • Bergi
    Bergi over 11 years
    element.data? Are you sure you didn't mean dataset?
  • the system
    the system over 11 years
    @Bergi: Thanks, that's what I meant. Fixed.
  • Isti115
    Isti115 about 11 years
    Thank you! That was exactly what I was looking for!