jQuery: How to Set and Delete “Data”? With or Without Attr()?

Mixing up attr() and data() functions in jQuery to set some data might have lead to behaviour you wouldn't expect...

The easiest way how to prevent any errors is to be precise in using either attr() or data() function.

Not both at same time, as you can see in fiddle below, there is a big difference.

If you set “order” via attr(), you can access it also with data(“order”). But if you remove attribute “data-order”, the value is still available!

Otherwise, if you set it with data(), attribute is not generated.

For debugging purpose, it is easier to work with attr() function, because you can see it directly in HTML code.

On other hand, data() might be preffered, if you expect to test HTML elements if having data. There is prepared hasData() function, while equivalent “hasAttr” doesn’t exist.