Lai32290
Lai32290

Reputation: 8558

How can I implement a non-jQuery version of data()?

I'm re-code a plugin jQuery I created, so I want take for create in pure Javascript

Most functions I can make fallowing YouMightNotNeedjQuery reference, but I don't have any idea to implement jQuery.data function for use in my plugin.

How to can I implement this function with Javascript pure?

Upvotes: 3

Views: 91

Answers (2)

Kevin Lynch
Kevin Lynch

Reputation: 24723

You can do it via datasets

HTML

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

Javascript

var article = document.getElementById('electriccars');

article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

Reference: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Edit as per comment

HTML

<article id="electriccars">
    ...
</article>

Javascript

var article = document.getElementById('electriccars');
article.setAttribute('data-columns', '3');

Example:

If you use getAttribute() the value is treated as a string, therefore it is not a like for like usage of jQuery .data as .data will assign objects and arrays to the data attr.

If you use dataset you will get a like for like usage as per jQuery.

Fiddle https://jsfiddle.net/69ukrpcf/

var myArr = ['item1', 'items2'];

jQuery Version

$('#one').data('foo', myArr);
var one = $('#one').data('foo');
console.log(one);

NON jQuery Version

var div = document.getElementById('two');
var two = div.dataset.foo = myArr;
console.log(two);

Upvotes: 4

Carlos Delgado
Carlos Delgado

Reputation: 3065

Read this article about how to work with data attributes here.

There are many ways to retrieve a data attribute with javascript :

var domElement = document.getElementById('randomid');
var articleId = domElement.getAttribute('data-articleid');
console.log(articleId);//Outputs 123

You can use too the datasets property of the dom element, however element.dataset will fail in old IE.

Upvotes: 0

Related Questions