daryl daryl - 2 months ago 11
jQuery Question

jQuery attribute name contains

I'm trying to target attributes names which contains a certain word & not in the kind of way you're thinking.

Lets say I have:

<div data-foo-bar="hello"></div>


How can I target elements which have
'data-foo'
in the attribute name?

Answer

I don't think you can target attribute names the same way you target attribute values. You can, however, use .filter() to do this somewhat efficiently:

$('div').filter(function() {
  for (var property in $(this).data()) {
    if (property.indexOf('fooBar') == 0) {
      return true;
    }
  }

  return false;
});‚Äč

Notice that data-foo-bar has been converted to fooBar.

Demo: http://jsfiddle.net/Tyj49/3/