-1

I am attempting to add a data attribute to an element on document.ready in order to set a default loading status.

I currently have:

jQuery(document).ready(function($) {
    $('#menu-primary-navigation li.isMobile').data('status','closed');
)};

I was expecting to see the following HTML

<li class="isMobile" data-status="closed" >foo</li>

However I don't seem to see any data attribute added. Am I using .data() incorrectly?

Francesca
  • 26,842
  • 28
  • 90
  • 153

2 Answers2

3
$('#menu-primary-navigation li.isMobile').attr('data-status','closed');

Here is a little jsfiddle to show how this works: http://jsfiddle.net/o3mLb53r/

jQuery data() function doesn't do what you think it does, it doesn't pertain to the data attributes.

Thomas Stringer
  • 5,682
  • 3
  • 24
  • 40
3

data() will not add an actual data-* attribute to your element when used as a setter. Instead, it will

Store arbitrary data ...

Although it can read from an existing data-* attribute when used as a getter

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

For more information on how this arbitrary data is stored, see Where is jQuery.data() stored?

Use attr() instead

$('#menu-primary-navigation li.isMobile').attr('data-status','closed');
Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53