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?
$(this).data('fulltext')
will work as attributes are lower cased. But indeed, you should set it as:data-fulltext
ordata-full-text
. For the later, then:$(this).data('fullText')
would work, using camel case syntax – ApiarianI know that .attr() is deprecated
attr() is not deprecated, this is the method to use to set/get attribute, not property – Apiarianprop
orattr
? – Foreshowdata()
instead but you should rewrite this attribute to use:data-fulltext="This is a span element"
– Apiarian