set/get dynamically custom attribute

28,188

Solution 1

I tested your code on IE7/8

var myInput = document.getElementById('myInput');
myInput.setAttribute('custom-attr', 'custom-value');
alert(myInput.getAttribute('custom-attr'));

and it runs fine. Does that simple test case fail for you, or are you actually doing something different?

You can use bracket notation

var myInput = document.getElementById('myInput');
myInput['custom-attr'] = 'custom-value';
alert(myInput['custom-attr']);

If you did not have the - in the name, you can use dot notation

var myInput = document.getElementById('myInput');
myInput.customAttr = 'custom-value';
alert(myInput.customAttr);

Solution 2

Your code works just fine on IE6, IE7, IE8, FF, Chrome, Opera.

Share:
28,188
ritmas
Author by

ritmas

Updated on August 30, 2020

Comments

  • ritmas
    ritmas almost 4 years

    Major modern browsers support setting/retrieving custom attribute dynamically, except IE-family. How can I set/get my custom attribute in all browsers?

    This is what I've tried so far:

    HTML:

    <input id="myInput" type="text" />
    

    JS:

    var myInput = document.getElementById('myInput');
    myInput.setAttribute('custom-attr', 'custom-value');
    alert(myInput.getAttribute('custom-attr'));
    

    or

    var myInput = document.getElementById('myInput');
    var customAttr = document.createAttribute('custom-attr');
    customAttr.value = 'custom-value';
    myInput.setAttributeNode(customAttr);
    alert(myInput.getAttribute('custom-attr'));
    

    In both cases IE alert() returns null.

  • lonesomeday
    lonesomeday almost 13 years
    Those aren't actually attributes; they're properties.
  • Wladimir Palant
    Wladimir Palant almost 13 years
    A note to help finding additional information on Google: this feature is called "expando properties".