4
<div id="story">
<p data-x="0">lorem ipsum...</p>
<p data-x="3">lorem ipsum...</p>
<p data-x="10">lorem ipsum...</p>
</div>

js

$("#btnleft").click(function(){
    var part = 1;
    var a = $("#story > p").eq(part);
    var b = a.dataset["data-x"];
    console.log (b);
});

I expect 3 as a result, but console says: Cannot read property 'data-x' of undefined

0

2 Answers 2

11

There is no property called 'dataset' in a jquery object. You need to extract the data-attribute by changing

 var b = a.dataset["data-x"];

to

var b = a.data("x"); 

// or 

var b = a.attr("data-x");
0
4

eq returns jQuery object. You need to use $.data() function. For example:

$("#btnleft").click(function(){
    var part = 1;
    var $a = $("#story > p").eq(part);
    var b = $a.data('x');
    console.log(b);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.