1

I'm trying to implement a jQuery selector which selects all the elements with data-xy-* attributes. I know how to select elements if we know the complete data attribute:

$("[data-xy-a]") will give me all the elements which have a data attribute data-xy-a

My problem is that the element can have any value instead of a. I want something like:

$("[data-xy-*]")
TylerH
  • 20,799
  • 66
  • 75
  • 101
CC7589
  • 133
  • 1
  • 12
  • I can get a list of data attributes with `.data()` but I need elements with `data-xy-*` attributes. Yes, I can iterate through the `.data()` list and check for keys starting with `xy`, but is there any other simple solution? – CC7589 Sep 17 '14 at 19:40
  • @DvS: Because I'm not selecting on the basis of value. I'm looking for selecting on a custom key – CC7589 Sep 17 '14 at 19:42

1 Answers1

0

There is no selector for this (as far as I know) but you can filter them out yourself...

$.expr[':'].dataStartsWith = function (elem, index, not) {
  var data = $(elem).data();
  return Object.keys(data).some(function (key) {
    return key.indexOf(not[3]) === 0;
  });
};

$(':dataStartsWith("xy")');

Just bear in mind data attribute names are converted to camelcase in dataset so to match data-xy-z-* you will need to use $(':dataStartsWith("xyZ")');

Jan
  • 8,011
  • 3
  • 38
  • 60