removeData() jquery method not working

turbo2oh picture turbo2oh · May 17, 2013 · Viewed 29k times · Source

I think I'm using removeData correctly but it doesn't seem to be working, here's what I'm seeing in the dev console, could anyone explain what I'm doing wrong?

I'm outputting the current data attribute value, calling removeData, then outputting the value again and its still there.

$('.questionList > li').eq(1).data('fieldlength')
3
$('.questionList > li').eq(1).removeData('fieldlength');
[
<li class=​"questionBox" data-createproblem=​"false" data-fieldlength=​"3" data-picklistvalues data-required=​"true" data-sfid=​"a04d000000ZBaM3AAL" data-type=​"Text">​
<div class=​"questionLabel">​Birthdate​</div>​
</li>​
]
$('.questionList > li').eq(1).data('fieldlength')
3

Answer

Iain Collins picture Iain Collins · Oct 6, 2013

There is bit of gotcha I wanted to clarify in case anyone else stumbles upon it...

If you have HTML5 data-* attributes on an element you need to use jQuery's removeAttr() instead of removeData() if you want to remove them from the element in the DOM.

For example, to actually remove a data attribute from an element you need to use:

$({selector}).removeAttr('data-fieldlength');

You can read values like this with $({selector}).data('fieldlength') but removeData() doesn't actually remove them if they are HTML attributes on an element present in the source of the page (it just deletes it in memory, so that if you query it again with jQuery it appears to have been removed).

Personally I think this behaviour is broken and I'm sure catches a lot of people out.