0

I can do this:

$('#someid').data('dataIdentifier', 'someVariable');

And in my understanding I can do this:

document.getElementById('someid').dataIdentifier = someVariable;

What are the pros of using jQuery for this versus raw JavaScript?

2 Answers 2

2

From the documentation for jquery.data:

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page.

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know about the jQuery method, but a "pure javascript" approach is to use setAttribute(). setAttribute is the same as what happens when you attach arbitrary data attributes in the html. You can use getAttribute to read it.

document.getElementById('someid').setAttribute("dataIdentifier", "someVariable");

One advantage is that it will show up in the innerHTML property, which plain old properties will not. The disadvantage is you are limited to strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.