jQuery .attr() seems to be case sensitive
I have a select
element with few custom attributes that I use to validate it on the f开发者_JAVA百科ly and display appropriate messages. Attribute's name is camel cased as in
<select validationMessage="Must select something" ... >...
The problem is that in jQuery version older than 1.6 .attr()
seems to be case sensitive. What's even more problematic, that it won't fetch originally cased attributes. This works the same in Firefox in Chrome, but works as expected (case insensitive as it should be) in Internet Explorer. It's also interesting that any casing (except original one) works.
Here's a JSFiddle example of this issue. You can change jQuery lib version on the left and hit "Run" to check how it works with other versions.
How am I about to mitigate this issue?
jQuery changed the way attr()
works in 1.6. Before this version, attr()
mostly mapped directly to properties under the hood — not attributes as one might think. Since DOM property names are usually single words, jQuery converted most strings passed to lower case and made exceptions for the few property names that were camel-cased. The reason jQuery behaved this way was to deal with browser inconsistencies and bugs in getAttribute()
and setAttribute()
.
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method. source
In 1.6, attr()
maps to getAttribute()
under the hood, and the new prop()
method retrieves the property values.
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() only retrieves attributes. source
If you replace attr()
with the javascript equivalent getAttribute()
, it seems to not be case sensitive.
The only drawback is that you have to get()
the js object first :
sel.get(0).getAttribute("validationMessage")
See the result here
精彩评论