17

I'd like to know more about using data-* attributes with HTML and its use within jQuery. I'm simply trying to retrieve data-attribute-name="a value" with .data() and or .attr() both are logging as 'undefined' with the following methods below. How do I use the data- attribute to pass values with jQuery?

HTML

<li class="als-item">
    <a data-loc-subject="test value">
        <img src="clock.png"/>
    </a>Beach
</li>

JS

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

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

jsFiddle

4
  • The second one should work, the first one, not so much. If none work you would probably have to post the HTML as well for us to spot the problem. Commented Aug 11, 2013 at 0:25
  • 1
    Note that .data already takes the "data-" into account, and applies some other "tricks". Also, inside the click, $(this).. is sufficient. Please post a minimal jsfiddle.net test-case to reproduce the behavior. Commented Aug 11, 2013 at 0:25
  • Just did. Still have undefined... Hmm Commented Aug 11, 2013 at 0:27
  • You're targeting the wrong element, posted an answer. Commented Aug 11, 2013 at 0:30

4 Answers 4

31

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

Sign up to request clarification or add additional context in comments.

2 Comments

Also, data() only retrieves the attribute the first time if the internal data object does not have that key, after that it uses the internal value. This is important as anything that updates the actual attribute will not update the internal data object, so consistency is key.
Can you explain more regarding internal data and internal value? Also, seems like .data() could replace my use of JS's getElementById() ?
3

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

Comments

1
<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)

Comments

0

set the data attribute as per your condition

 <a id="edit" data-lan="my-data" onclick="onEdit(this)">Edit</a>

    function onEdit(obj) {
     console.log(this.getAttribute("data-lan")); //my-data
    }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.