Xinrui Ma Xinrui Ma - 6 months ago 8
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
console.log($('#ssd').data());
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") {
item.name = value.split(":")[0];
item.number = value.split(":")[1];
dataIWant.push(item);
}
});


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

Answer

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:

data-foo-bar
data-foo-bar-baz

but not:

data-foo-someting
data-something

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:
$('p:data-starts-with(foo-bar)').css({color:"red"});  

// To get a list of data attributes:
$('p:data-starts-with(foo-bar)').each(function(i, el){
  console.log( el.dataset );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>