Xinrui Ma Xinrui Ma - 4 months ago 6x
Javascript Question

How to get all data-* attributes by Prefix

I have a tag like this:

<a href="#" id="ssd" data-toggle="popover" data-info1="demo text: 1" data-info2="demo text: 2" data-info3="demo text3">Link</a>

When I click this link, I have a function like this

$('#ssd').click(function (event) {
var customData;
// Code to get all the custom data in format like data-info*

Note, the data-info* like attributes could be any number, that means you could see 1 one of them, named data-info1, or there of them, named data-info1, data-info2, data-info3.

How would I do that, I looked up the JQuery selectors, something like Attribute Starts With Selector [name^="value"] won't work because the variation here is on name...

If I
I will get an object with extra attributes that I don't need,
toggle: "popover", bs.popover: Popover

Any suggestions?

This is what I did:

dataFullList = $(this).data();
$.each(dataFullList, function (index, value) {
if (index !== "toggle" && index !== "bs.popover") { = value.split(":")[0];
item.number = value.split(":")[1];

So I will get a
array without stuff I don't need.


Target all elements which data-* starts with

Here's a custom jQuery selector that will help you to:

Given the data-foo-bar prefix , target the following elements:


but not:


jQuery.extend(jQuery.expr[':'], { 
  "data-starts-with" : function(el, i, p, n) {  
    var pCamel = p[3].replace(/-([a-z])/ig, function(m,$1) { return $1.toUpperCase(); });
    return Object.keys(el.dataset).some(function(i, v){
      return i.indexOf(pCamel) > -1;

// Use like:

// To get a list of data attributes:
$('p:data-starts-with(foo-bar)').each(function(i, el){
  console.log( el.dataset );
<script src=""></script>

<p data-foo-bar="a">I have data-foo-bar</p>
<p data-foo-bar-baz="b" data-extra="bbb">I have data-foo-bar-baz</p>
<p data-bar="a">I have data-bar DON'T SELECT ME</p>
<p data-something="b">I have data-something DON'T SELECT ME</p>