1

I have

<div data-text="This is a text">...</div>

I need to access the data-text in javascript. It works with alert($('div').data('text')); but not with alert($.data($('div'), 'text')); gives me undefined.

WHY?

LINK: http://jsfiddle.net/tvDzP/2/

(For performance issues I use element.attr('data-text') to retrieve the text )

1
  • please post example of non-working code. Maybe $ is not defined (jQuery run in non-conflict mode)? Commented Aug 22, 2012 at 11:22

2 Answers 2

1

Normally $.data expects a DOM node, not a jQuery object.

$('div').data('text') // correct
$.data($('div')[0], 'text') // correct
$.data($('div'), 'text') // incorrect

However, for the data-* attributes, $.data doesn't work unless the value has already been retreived once by $(element).data().

From the docs:

Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.

Demo

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

Comments

0

element has to be a DOM element, not a selector or a jQuery object:

$.data($('div')[0], 'text')

http://jsfiddle.net/CGck6/

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.