Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data stored in a DOM element?

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?

like image 637
sawa Avatar asked Oct 24 '25 11:10

sawa


2 Answers

You are confusing the data() method with the element's data attribute.

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:

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

Solution 2 - data as an object

Using the data() method you can manually attach information to the element:

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

Note how in this case 'data' is just an arbitrary name for a key in the element's data object. For more on the data() method see the jQuery manual


Solution 3 - data as an object and HTML5 attribute

I believe your original intention was to query the data attribute as an HTML5 data-attribute, that according to the jQuery documentation should be automatically 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 named data but rather data-something. For example:

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

Which you can then access with jQuery's data() method:

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

Note how data-something is accessed with data('someting'), since jQuery automatically removes the data- prefix.

like image 96
Boaz Avatar answered Oct 26 '25 02:10

Boaz


you need to access the attribute with the attr function.

$(".bar").hover(function() {
     alert($("#"+$(this).attr('data')));
   });
like image 37
mercsen Avatar answered Oct 26 '25 00:10

mercsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!