Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: 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? 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?

like image 810
Al.G. Avatar asked May 11 '14 11:05

Al.G.


People also ask

How get data attribute value in jQuery?

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" ).

How do I find data attributes?

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.

How do you select an element with a data attribute?

[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.

How do you check if data attribute exists in jQuery?

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 .


Video Answer


2 Answers

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.

like image 87
Darin Dimitrov Avatar answered Oct 12 '22 17:10

Darin Dimitrov


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/

like image 37
mrdeveloper Avatar answered Oct 12 '22 15:10

mrdeveloper