In my html I have a span
element:
<span class="field" data-fullText="This is a span element">This is a</span>
And I want to get the data-fullText
attribute. I tried these two ways, but they didn't work (the both return undefined
):
$('.field').hover(function () { console.log('using prop(): ' + $(this).prop('data-fullText')); console.log('using data(): ' + $(this).data('fullText')); });
Then I searched and found these questions: How to get the data-id attribute? and jquery can't get data attribute value.
The both's answers are "Use .attr('data-sth') or .data('sth')"
.
I know that .attr()
is deprecated (in jquery-1.11.0, which I use), but, however, I tried it.
And it workded!
Can someone explain why?
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
[attribute=”value”]: It selects the elements with a specified attribute and value. [attribute~=”value”]: It selects the elements with an attribute value which contains a specified word. [attribute|=”value”]: It selects the elements with the specified attribute which starts with the specified value.
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
You could use the .attr()
function:
$(this).attr('data-fullText')
or if you lowercase the attribute name:
data-fulltext="This is a span element"
then you could use the .data()
function:
$(this).data('fulltext')
The .data()
function expects and works only with lowercase attribute names.
1. Try this: .attr()
$('.field').hover(function () { var value=$(this).attr('data-fullText'); $(this).html(value); });
DEMO 1: http://jsfiddle.net/hsakapandit/Jn4V3/
2. Try this: .data()
$('.field').hover(function () { var value=$(this).data('fulltext'); $(this).html(value); });
DEMO 2: http://jsfiddle.net/hsakapandit/Jn4V3/1/
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