How to get the value of data attribute using JQuery in core?

Tags: , ,

I want to get the value of the custom attribute by jquery. I use this code to do that but in console it show “undefined”:

var correct = $("div").data("correct");

this is the html:

<div data-correct="@classCorrect.Answer">....</div>

also, I used “attr” to do that but that was the same too and shows “undefined”. And I don’t want to use “id” for the selector. I want it to show 3 as it is in “@classCorrect.Answer”.


If there are serverl divs with the data-correct attribute, you should give them the same class or name

Such as:

<div class="test" data-correct="1">A</div>
<div class="test" data-correct="2">B</div>
<div class="test" data-correct="3">C</div>

And when you use the class or name selector, the result is an array of these elements, you should traverse it to get each element then get its attribute value.

$(function () {
    var datalist = $(".test");
    $.each(datalist, function (i,value) {

Source: stackoverflow