Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set/get dynamically custom attribute

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.

like image 698
ritmas Avatar asked Aug 29 '11 13:08

ritmas


People also ask

How to get value of custom attribute in JavaScript?

Using getAttribute and setAttribute You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes. The getAttribute method will either return null or an empty string if the given attribute does not exist.

How do I set custom attributes in powershell?

These can be found by right-clicking on a mailbox in the Exchange Management Console, choosing properties and then clicking on the custom attributes button in the bottom right-hand corner of the window. There are 15 unique attributes that can be used for whatever your needs are.

How to add a custom attribute in Braze?

To create and manage custom attributes in the dashboard, go to Manage Settings > Custom Attributes. From this page, you can view, manage, or blocklist existing custom attributes, or create a new one.


2 Answers

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);
like image 79
epascarello Avatar answered Oct 21 '22 07:10

epascarello


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

like image 32
Paktas Avatar answered Oct 21 '22 06:10

Paktas