I have a DOM element of class bar that stores data foo, which is the id of another DOM element.
<div class="bar" data="foo">...</div>
When I hover over such element, 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 hover, I get this error:
Uncaught Error: Syntax error, unrecognized expression: #[object Object]
What am I doing wrong, and how can I fix it?
You are confusing the
data()method with the element’sdataattribute.The
data()method returns an unrelated object of data attached to the element and not the string you are looking for.Solution 1 – data as an attribute
To get the value you’re looking for in your example, you should query the attribute with the
attr()method:Solution 2 – data as an object
Using the
data()method you can manually attach information to the element:Note how in this case
'data'is just an arbitrary name for a key in the element’s data object. For more on thedata()method see the jQuery manualSolution 3 – data as an object and HTML5 attribute
I believe your original intention was to query the
dataattribute as an HTML5 data-attribute, that according to the jQuery documentation should beautomatically pulled in to jQuery's data object.However, note that according to the HTML5 specification, HTML5 data-attributes are expected to have a
data-prefix. So in order for your example to work, the attribute cannot be nameddatabut ratherdata-something. For example:Which you can then access with jQuery’s
data()method:Note how
data-somethingis accessed withdata('someting'), since jQuery automatically removes thedata-prefix.