jQuery attribute name contains

Solution 1:

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/

Solution 2:

I'm not sure you can do that. I've had a peek at the API and you only seem to be able to do deeper partial matching on the value, not the attribute name itself.

I'm going to give you the potentially frustrating advice of, "don't do this". ;-) In essence, what you're after is a bunch of divs that match a more general category. Not just data-foo-bars, but ALL data-foos! Why not just give all data-foos a classname that you can select from, or a separate attribute like data-foo="true"?

In other words, rather than sticking strictly to the question as asked, I'd be curious to know what the use case is so that maybe a lateral move in thinking can solve your problem just as effectively. Many ways to skin a cat and all that.

Solution 3:

This is just an alternative solution. If you can ensure the attribute's name you're looking for is not present in the element text, what you could do is getting the outerHtml value of the element and then make a substring search:

$("elementsToCheck").each(function () {
    var elemHtml = $('<div>').append($(this).clone()).html(); //clone to get the outerHTML
    if (elemHtml.indexOf("attributeName") >= 0) {
        // current element contains the attribute with name "attributeName"
    }
});

Hope this helps.