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.
Author by
ritmas
Updated on August 30, 2020Comments
-
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()
returnsnull
. -
lonesomeday almost 13 yearsThose aren't actually attributes; they're properties.
-
Wladimir Palant almost 13 yearsA note to help finding additional information on Google: this feature is called "expando properties".