11

Consider following code:

(function () {
  'use strict';
  delete document.body.dataset.state;
})();

where body dataset is empty. Safari treats all DOMStringMap values — well, I guess so — as ReadOnly, and their enumerable, configurable and writable descriptor values are all set to false. This causes the TypeError: Unable to delete property to appear in the mentioned above example.

But in Chrome dataset property descriptor values are set to true (can be checked with Object.getOwnPropertyDescriptor()), and deleting inexistent attribute does not throw the error.

So, what behavior is correct? The spec says about readonly dataset, but writable DOMStringMap, so I assume dataset properties must be deletable. Am I missing something?

P.S.
  • 15,970
  • 14
  • 62
  • 86
evenfrost
  • 414
  • 5
  • 14
  • 3
    Without looking into it deeper, just as a reminder, the spec isn't absolute and defined down to the detail, a surprising amount of things is implementation-specific. – Etheryte Mar 10 '15 at 20:38
  • The spec does not seem to say what syntax should be supported to remove a dataset attribute. The general public consensus among developers using other browsers is to clear the value by setting it to an empty string or to use `delete`, but there does not seem to be a written standard on this. My personal opinion is that Safari is probably wrong here, but it is what it is if you have to make code work with it. – jfriend00 Jun 09 '15 at 04:11
  • Found any solution to this? – Ankur Aggarwal May 02 '16 at 13:27
  • @AnkurAggarwal nope, using `removeAttribute('data-whatever')` for this. – evenfrost May 03 '16 at 09:38
  • What exactly do you mean by "*where body `dataset` is empty*" - can you post the respective markup? – Bergi Oct 13 '16 at 12:15
  • Did you call `Object.getOwnPropertyDescriptor` for the `dataset` property or for the `state` property? It's not exactly clear from your question – Bergi Oct 13 '16 at 12:19
  • You could always try `document.body.removeAttribute('data-foo')`. –  Oct 13 '16 at 12:59

1 Answers1

2

Its probably because of strict mode.

Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):

'use strict';
delete Object.prototype; // throws a TypeError

You may want to take a look at this documentation

Also you can try set object value to undefined, its a little hairy but works..

Tamer Aktaş
  • 416
  • 4
  • 13