Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery .data() function is not accessing HTML5 camel-case data attribute

Tags:

html

jquery

I have a button in my web page:

<button class="slideToggle" data-slideToggle="slider">SlideToggle</button>

When this button is clicked I am trying to access the data that is stored inside the data-slideToggle attribute by useing the following code, but I get nothing.

$('body').on('click', '.slideToggle', function(){
    alert($(this).data('slideToggle'));
});

but it works when I use:

alert($(this).attr('data-slideToggle'));

This problem occurs when I use camel-case data attribute. I am very new to HTML5 and jQuery and I can not figure out what is going wrong with it.

like image 514
S.K Avatar asked Mar 18 '23 12:03

S.K


2 Answers

All the previous answers miss one thing: you actually can work with existing HTML structure. Consider this:

$('body').on('click', '.slideToggle', function(){
    alert($(this).data('slidetoggle')); // wait, what?
});

To understand what happens here, it's crucial to check the following lines in jQuery source code:

name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );

See, jQuery here follows the convention of Dataset API, converting the fooBar property into data-foo-bar name of the element's attribute.

In your case, that converts 'slideToggle' to 'data-slide-toggle' - and there's no such attribute in your HTML, apparently.

However, data('slidetoggle') works fine, as getAttribute by default performs a case-insensitive search among Element's attributes. Therefore, you might even wrote that one as...

<button data-sLiDeToGgLe="l33t!"></button>

... and it still would have worked. )

Still, I'd rather recommend following the Dataset API convention, breaking camelCased complexWord data attributes into hyphenated complex-word notation.

like image 78
raina77ow Avatar answered Mar 21 '23 01:03

raina77ow


Because that's not how you should use it. You can only use lowercase attributes and that's why it isn't working for you.

Change <button class="slideToggle" data-slideToggle="slider">SlideToggle</button> to

<button class="slideToggle" data-slidetoggle="slider">SlideToggle</button>

and access it like alert($(this).data('data-slidetoggle'));

attr works on any custom attribute so it works there too, but data has some rules to follow.

Spec says

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters.

like image 26
Amit Joki Avatar answered Mar 21 '23 02:03

Amit Joki