drake035
drake035

Reputation: 2877

Can't set value to data attribute with jQuery

From some reason I can't figure out, the $('element').data('data_attribute_name', 'value'); syntax doesn't work here:

HTML:

<ul class="main_menu__list" data-scheme="light">
...
</ul>

JS:

$('.main_menu__list').data('scheme', 'dark');
$('.main_menu__list').css('border', '10px solid yellow');

The second line does work (yellow border applied), the second one does nothing. why?

Upvotes: 2

Views: 856

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The first line is working fine. The data() method stores the values in an in-memory cache so that it's faster (at least in theory) due to having to query the DOM less often. It does not update the DOM at all.

So long as you also use the getter of data() to retrieve the value this works absolutely fine:

var $list = $('.main_menu__list');

$list.data('scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main_menu__list" data-scheme="light"></ul>

even using attr() as suggested in another answer it still doesn't change it!

Yep, it does. You can check it in the DOM inspector after running this snippet:

var $list = $('.main_menu__list');

$list.attr('data-scheme', 'dark').css('border', '10px solid yellow');

// to retrieve the attribute:

console.log($list.data('scheme')); // 'dark'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main_menu__list" data-scheme="light"></ul>

Upvotes: 2

kanzari
kanzari

Reputation: 87

Use this :

$('.main_menu__list').attr('data-scheme', 'dark');

instead of this :

$('.main_menu__list').data('scheme', 'dark');

Upvotes: 2

Related Questions