Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Lai32290 Avatar asked Jan 20 '26 08:01

Lai32290


1 Answers

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);
like image 129
Kevin Lynch Avatar answered Jan 22 '26 21:01

Kevin Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!