0

I want to get data-* (data dash, or dataset) values without knowing what follows after the dash. Ex:

<div data-whatever="value" data-another="value2"></div>

I don't know how the "whatever" or "another" parts are named, but I need to grab the value. Is it possible with JavaScript?

Because

document.querySelectorAll('[data-*]')

is not a valid selector

Porkopek
  • 895
  • 9
  • 20
  • Not sure this is supported natively, but you can do this with jQuery or another utility library. See https://stackoverflow.com/q/5376431/3966682 – d4nyll Jun 27 '19 at 11:09

2 Answers2

2

The dataset property of an element contains all the data-* attributes. This is a DOmStringMap whose keys are the attributes with the data- removed and the remaining words converted to camelCase.

I don't think there's a way to select just the elements with any data attribute, so you'll have to select all elements and filter them yourself by checking the length of element.dataset.

var dataElements = Array.from(document.querySelectorAll('*')).filter(el => Object.keys(el.dataset).length > 0);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Try something like this:

In the example I've created an Id for the div

<div data-whatever="value" data-another="value2" id="test"></div>

And after I got the element by Id, retrieving the dataset property which returned an DOMStringMap

data = document.getElementById('test').dataset;
console.log(data);

And finally I just got the keys from the returned object.

Object.keys(data).map(function(el) {
    console.log(el)
});

I hope it helps you :)

Camilo Silva
  • 83
  • 1
  • 1
  • 8