Get Subset Data From Custom Data Attributes - dataSubset

Get Subset Data From Custom Data Attributes - dataSubset
File Size: 33.6 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

What Is Custom Data Attribute:

A custom HTML data-* attribute enables you to make up your own HTML attributes where you can place any custom information to be exchanged between the HTML and its DOM representation by scripts.

<div id="element"
     data-jquery="jqueryscript">
     Just An Example
</div>

In today's web development, it is easy to access to custom HTML data-* attributes with jQuery or Vanilla JavaScript as shown below:

Get data attributes with jQuery:

You can read/write custom data attributes with jQuery's attr method:

// Get value
var value = $('#element').attr('data-jquery');
// Change value
$('#element').attr('data-jquery', yourNewValue);

Get data attributes with native JavaScript:

You can read/write custom data attributes with dataset function:

const el = document.querySelector('#user');

// get value
el.dataset.jquery === 'jqueryscript'

// set value
el.dataset.jquery = 'jqueryscript.net'; 

What About Subset?

dataSubset is such a jQuery plugin that enables you to get the subset data from custom HTML data-* attributes in your elements.

How To Use It:

1. Load the jquery.dataSubset.js after jQuery.

const el = document.querySelector('#user');

// get value
el.dataset.jquery === 'jqueryscript'

// set value
el.dataset.jquery = 'jqueryscript.net'; 

2. Insert your own information into data-* attributes as follows:

<div class="data-subset-example"
     data-js-jquery="jqueryscript.net"
     data-js-css="cssscript.com"
     data-website="https://www.jqueryscript.net">
</div>

3. The JavaScript to get all data. This will return an object containing all properties & values.

var $example = $('.data-subset-example');
var allData = $example.data();
console.log('all_data =>', allData);

// returns
{
  website: "https://www.jqueryscript.net",
  jsCss: "cssscript.com",
  jsJquery: "jqueryscript.net"
}

4. The JavaScript to get subset data.

var subsetData = $example.dataSubset('js');
console.log('subset_data =>', subsetData);

// returns
{
  css: "cssscript.com",
  jquery: "jqueryscript.net"
}

This awesome jQuery plugin is developed by askalione. For more Advanced Usages, please check the demo page or visit the official website.