How do I get the data stored in a DOM element?

I have a DOM element of a class bar

that stores data foo

that is the ID of another DOM element.

<div class="bar" data="foo">...</div>

      

When I hover over an element like this, I want to get the DOM element that the data (id) points to. I did this:

$(".bar").hover(function(){alert($("#"+$(this).data()));});

      

But when i find i get this error:

Uncaught Error: Syntax error, unrecognized expression: #[object Object]

      

What am I doing wrong and how can I fix it?

+3


source to share


2 answers


You are confusing a method data()

with an attribute data

.

The method data()

returns an unbound data object attached to the element, not the string you are looking for.


Solution 1 - data as an attribute

To get the value you are looking for in your example, you have to query the attribute using the method attr()

:

$(".bar").hover(function(){alert($("#"+$(this).attr('data')));});

      


Solution 2 - data as object

Using the method data()

, you can manually bind information to an element:

$('.bar').data('data','foo');
$(".bar").hover(function(){alert($("#"+$(this).data('data')));});

      



Note that in this case, 'data'

is just an arbitrary name for the key in the item data object. For more details on the method data()

see the jQuery manual


Solution 3 - data as object and HTML5 attribute

I believe your original intent was to request the attribute data

as an HTML5 data attribute, which the jQuery documentation is supposed to submit automatically pulled in to jQuery data object

.

Note, however, that according to the HTML5 specification, HTML5 data attributes must be prefixed data-

. So for your example to work, the attribute cannot be named data

, but rather data-something

. For example:

<div class="bar" data-something="foo">...</div>

      

What you can get with jQuery method data()

:

 $(".bar").hover(function(){alert($("#"+$(this).data('something')));});

      

Note what to data-something

refers to data('someting')

as jQuery removes the prefix automatically data-

.

+7


source


you need to access the attribute using the attr function.



$(".bar").hover(function() {
     alert($("#"+$(this).attr('data')));
   });

      

+4


source







All Articles