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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With