Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data attribute to div with jQuery

I am trying to set a data attribute to a div which previously doesn't have any value.

<div></div>

with jQuery, the first method (data) doesn't do anything, however the attr method works correctly.

var div = $('div');
div.data('superhero_one','batman');
div.attr('data-superhero_two','spiderman');

http://jsfiddle.net/5bT8p/

Am I using incorrectly the data function?

like image 860
Alvaro Avatar asked Dec 09 '25 09:12

Alvaro


2 Answers

It does work !

The actual thing behind that is , you can't see actual attribute when you use .data() because jquery sets that internally. but .attr() adds an attribute to the element which you can inspect.

see this demo --> http://jsfiddle.net/5bT8p/1/

like image 50
Mohammad Adil Avatar answered Dec 11 '25 22:12

Mohammad Adil


$("div").data("superhero_two","spiderman");

is the right syntax. But when inspecting, I'm only seeing data-superhero_two="spiderman" (as intended). The attribute from .attr is set in the DOM, and the .data is set in the JQuery object only.

By the way, use the document ready function to ensure its execution at the right time:

$(document).ready(function() {
    $("div").data("superhero_two","spiderman");
});
like image 25
Hannes Schneidermayer Avatar answered Dec 11 '25 22:12

Hannes Schneidermayer



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!