8

You can do [foo^="bar"] to match nodes which have the attribute foo with value starting with bar.

Is there a way to match nodes with an attribute name starting with a particular string? The use case of this is to match all nodes with a data-* attribute.

Edit: the reason I'm trying this is to avoid iterating over all the nodes looking for these attributes (for performance reasons). I'd be using querySelectorAll and its Sizzle polyfill for older browsers.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
jli
  • 6,523
  • 2
  • 29
  • 37

2 Answers2

4

One way is using .filter() method:

$('element').filter(function() {
    return $.grep(this.attributes, function(value) {
       return value.nodeName.indexOf('data') === 0;
    }).length;
});

http://jsfiddle.net/QACsw/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • `.lastIndexOf('data', 0) === 0` for extreme millerseconds difference as well. – Fabrício Matté May 23 '13 at 22:59
  • @FabrícioMatté: Won't make much of a difference, `$.grep` doesn't break out once the first `data-` attribute is found. – Blender May 23 '13 at 23:03
  • @Blender I know, I just meant that this operation would be a tad bit faster than `indexOf`. Here are the details http://stackoverflow.com/a/4579228/1331430 – Fabrício Matté May 23 '13 at 23:05
  • I didn't make this clear originally, but the reason I'm using a selector like this at all is to avoid iterating over all nodes/attributes (for perf reasons). Unfortunately anything less than a native solution wouldn't work, I think. – jli May 24 '13 at 00:42
4

It may be a little overkill, but you could write a custom selector:

$.expr[':'].attr = function (elem, index, regex_str) {
    var regex = new RegExp(regex_str[3]);

    for (var i = 0; i < elem.attributes.length; i++) {
        if (elem.attributes[i].name.match(regex)) {
            return true;
        }
    }

    return false;
};

Demo: http://jsfiddle.net/LBHwr/

So in your case, you'd do:

$('div:attr(^data)') // starts with
$('div:attr(foo$)')  // ends with

It's somewhat similar to the regular attribute selector syntax.

Blender
  • 289,723
  • 53
  • 439
  • 496