2

I have a select element with few custom attributes that I use to validate it on the fly 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?

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • See this http://stackoverflow.com/questions/3967869/writing-jquery-selector-case-insensitive-version – Tx3 May 18 '11 at 10:02
  • 1
    This is not a dupe of that question, that question is regarding selectors. – Andy E May 18 '11 at 10:22

2 Answers2

9

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

Andy E
  • 338,112
  • 86
  • 474
  • 445
2

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

Sylvain
  • 3,823
  • 1
  • 27
  • 32
  • I was aware of this DOM function but I'm not sure about its browser support and particularities. Isn't jQuery using the same function in the background anyway? – Robert Koritnik May 18 '11 at 10:05
  • @Robert Not before 1.6. The method in 1.5.2 is [elem[name]](https://github.com/jquery/jquery/blob/1.5.2/src/attributes.js#L351). – lonesomeday May 18 '11 at 10:09