Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery internally convert HTML5 data attribute keys to lowercase?

I am trying to conform my JavaScript coding style to my Zend coding style as much as possible, which is using camelCase. So, in my HTML5 data attributes, I am naming them as in this example:

<button class="action" data-actionClass="user" data-actionMethod="delete" data-actionRequest="/user/delete/user-id/1" data-actionComplete="{reload:users}">Delete User #1</button>
<div id="users" data-reloadRequest="/user/index"> ... </div>

Pretty unobtrusive way to harness Jquery for actions, but when I call $('.action').data(), the attribute names are converted to lowercase.

Any workarounds for this?

I never though JavaScript variables should have dashes in them, and I can't understand why jQuery is internally doing this for me? Or maybe it is HTML5?

like image 701
axiom82 Avatar asked Jan 08 '14 01:01

axiom82


People also ask

Should HTML attributes be lowercase?

3.4. Attribute names for HTML elements may be written with any mix of lowercase and uppercase letters that are a case-insensitive match for the names of the attributes given in the HTML elements section of this document; that is, attribute names are case-insensitive.

What is data attribute in jQuery?

The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

How pass data attribute value in jQuery?

$('selector expression'). attr('name','value'); First of all, specify a selector to get the reference of an element and call attr() method with attribute name parameter. To set the value of an attribute, pass value parameter along with name parameter.

How can custom attributes be defined in HTML5 for a?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.


2 Answers

If you use

data-action-method="delete"

then you can access the attribute with

$('.action').data('actionMethod')

This is part of the HTML5 DOM API:

The custom data attributes is transformed to a key for the DOMStringMap entry with the following rules:

  • any dash (U+002D) is removed;
  • any letter following a dash (U+002D), before its removal, is set in its uppercase counterpart.
like image 81
Felix Kling Avatar answered Oct 16 '22 15:10

Felix Kling


First off, see this part of the source code of JQuery, it assumes you have lower case attributes.

Secondly, by convention, all HTML5 attributes should be lowercase, see: http://www.htmlbasictutor.ca/html-tag-attributes.htm

Finally, be warned you may encounter futher problems if you insist on using upper cases, see Django: Unable to add UPPERCASE attribute name in HTML input element

like image 25
Daniel D Avatar answered Oct 16 '22 15:10

Daniel D