The HTMLElement class
attribute is not appropriate for storing application data; it is meant for presentational use only. I understand it was useful to use it in your previous CSS-based solution, but even in that case there are other, more appropriate attributes (e.g., data-*
attributes) which are “visible” to CSS. That said, depending on how you’re providing the State data to Select2, I have a couple of suggestions.
If you’ve got the state selections are hard-coded in your HTML as a <select>
element with child <option>
elements for each state, then why not use the standard value
attribute (e.g., <option value="CA">California</option>
)? The value of this attribute will be assigned to the “id” property of Select2’s internal item representation, and that property is directly accessible on the object representing the user’s selection.
If, for whatever reason, you can’t (or don’t want to) use the value
attribute, you can use a data-*
attribute (e.g., <option data-state-abbr="CA">California</option>
). The object that represents the user’s selection contains a property called “element” which holds a reference to the HTMLOption object (i.e, the <option>
element) that the user’s selection represents. You can use standard methods on that object to access those data attributes.
If you are providing the State data as a Select2 JavaScript data array, you can include whatever additional data fields you need in your individual item objects; those objects must contain “id” and “text” properties, but they can also contain any other properties you need, and those properties are directly accessible on the object representing the user’s selection.
I hope this helps. If not, it would be helpful if I could see your HTML and JavaScript code (perhaps you could put your page up on codepen.io, jsfiddle.net or another similar site).