Porkopek
Porkopek

Reputation: 1012

Get values of data-* attributes without knowing what follows after "data-"

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

Upvotes: 1

Views: 840

Answers (2)

Camilo Silva
Camilo Silva

Reputation: 93

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 :)

Upvotes: 2

Barmar
Barmar

Reputation: 780974

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);

Upvotes: 3

Related Questions