Set / get dynamically configured attribute

Major modern browsers support setting / retrieving a custom attribute dynamically, with the exception of the IE family. How can I set / get my custom attribute in all browsers?

This is what I have 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 .

+8
javascript cross-browser dynamic custom-attributes
source share
2 answers

I checked your code on IE7 / 8

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

and it works fine. Is a simple test happening for you, or are you really doing something else?

You can use parenthesis notation

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

If you didn’t have - in the name, you can use dot notation

 var myInput = document.getElementById('myInput'); myInput.customAttr = 'custom-value'; alert(myInput.customAttr); 
+12
source share

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

+2
source share

All Articles