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
.
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);