How do I use the data- attribute to pass values with jQuery?

<div id="someID" attr1="this is attr 1" data-attr-1="data attribute 1"></div>

You can find any element attribute using

$("#someID").attr('attr1') [or] $("#someID").attr('data-attr-1');

to target based on if the element has the attribute, you can do:

$("[attr1]") or $("[attr1='this is attr 1']") , which will return the element (not the attribute value)


You don't need to prefix the data name with the word data.

$( ".als-item > a" ).click(function(e) {
    e.preventDefault();

    var data = $('.als-item').data('loc-subject');
    var attrmethod = $('.als-item').attr('data-loc-subject');
        console.log(data);
        console.log(attrmethod);
});

http://jsfiddle.net/thinkingmedia/c6kYT/

The Difference Between The Two

You can hard code data value into the DOM using data attributes. For example;

<a href="#" data-john="smith">Something</a>
console.log($("a").data("john"));
// will output "smith"

That works because jQuery treats data differently from attributes. It will first check if the DOM element contains an attribute called data-john, and if it does return that value. If it does not contain that attribute it will look at internal data attached to the DOM element. If that data exists it will return that value.

When you set data using jQuery it will not update the attributes of the DOM element. It will attach the data to the DOM element internally. Therefore $("a").data("house","on fire"); will store the string "on fire" in the DOM element under a label "house". If you use the DOM inspector to look at the HTML. There will be no new attribute assigned to that element called data-house.

That is different from using the jQuery.attr() methods. Which directly modify a DOM element's attributes.

EDIT: Something to note is that in order to access the data attributes of some HTML element, you must select the element via some selector (id,class,etc). You cannot pass "this" to any method attribute on the element and use that argument to access the data. It will produce an undefined.

HTML

<li class="als-item">
    <button onclick="somefunc1(this)" id="mybutton" 
        data-loc-subject="test value">My Button</button>
</li>

JS

function somefunc1(button) {
  // this alert prints "undefined"
  alert($(this).data('loc-subject'));
  // this will print "test value"
  alert($('#mybutton').data('loc-subject'));
}

Plunker


The "data-" attribute prefix should be stripped off in your .data() call, so assuming:

<span class="als-item" data-loc-subject="foo">ohai</span>

it would be retrieved via:

console.log($(".als-item").data("loc-subject"));

Tags:

Jquery