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?



1. Try this: .attr()

  $('.field').hover(function () {
    var value=$(this).attr('data-fullText');

DEMO 1: http://jsfiddle.net/hsakapandit/Jn4V3/

2. Try this: .data()

$('.field').hover(function () {
    var value=$(this).data('fulltext');

DEMO 2: http://jsfiddle.net/hsakapandit/Jn4V3/1/


Change IDs and data attributes as you wish!

  <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>

$("#selectVehicle").change(function () {

Here is the working example: https://jsfiddle.net/ed5axgvk/1/


You could use the .attr() function:


or if you lowercase the attribute name:

data-fulltext="This is a span element"

then you could use the .data() function:


The .data() function expects and works only with lowercase attribute names.


This works for me

$('.someclass').click(function() {
    $varName = $(this).data('fulltext');

This is what I came up with:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='external-events'>
			<div class='fc-event' data='00:30:00' >30 Mins</div>
			<div class='fc-event' data='00:45:00' >45 Mins</div>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.