Al.G. Al.G. - 3 months ago 8
HTML Question

Get data attribute

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 using jquery? and jquery cant 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?

Answer

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

Comments