0

For example, I want to match all elements that have "data-foo" within any of their attributes:

<a data-foo="abc" href="#">I'm Matched</a>
<a data-foo-bar="abc" href="#">I'm Matched Too</a>
<a data-foo-bar-baz="abc" href="#">I'm Matched Too</a>

<a data-bar-foo="abc" href="#">I'm Not Matched</a>

I could easily loop through all of the elements and check myself but I wasn't sure if jQuery supported this type of selector.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jacob Kelley
  • 395
  • 3
  • 13

2 Answers2

1

check this fiddle...a little out there but maybe you could work off this

JSFiddle

$("a").each(function(){
    var element = $(this);
    var isItMe = 0;
        $(element[0].attributes).each(function() {
             if(this.nodeName.indexOf("data-bar") >= 0){
                isItMe = 1;
             }
        });
    if(isItMe == 1){
        $(this).css({"color" : "red"});  
    }
});
VIDesignz
  • 4,703
  • 3
  • 25
  • 37
0

Satpal's answer is pretty good (I like that the selector is restricted to only <a> elements; that will be a little faster than searching the whole DOM).

I would like to suggest, though, that you use multiple data attributes. For example:

<a data-foo="abc" href="#">I'm Matched</a>
<a data-foo="abc" data-foo-bar="abc" href="#">I'm Matched Too</a>
<a data-foo="abc" data-foo-bar-baz="abc" href="#">I'm Matched Too</a>

<a data-bar-foo="abc" href="#">I'm Not Matched</a>

Or classes:

<a class="foo" data-foo="abc" href="#">I'm Matched</a>
<a class="foo" data-foo-bar="abc" href="#">I'm Matched Too</a>
<a class="foo" data-foo-bar-baz="abc" href="#">I'm Matched Too</a>

<a data-bar-foo="abc" href="#">I'm Not Matched</a>

In in this way, you can match one one thing (either data-foo or class foo), and get the specificity you need as well.

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
  • 1
    I know I could easily add a class but that defeats the purpose of my question. I have no problem selecting these elements, I just want to select by a partial attribute name. – Jacob Kelley Feb 08 '14 at 20:05
  • (nod) I get it, but there's no way I know of to do that, so I'm just suggesting rejiggering your architecture a bit to provide some generic AND specific info. That is, "this thing is a foo, but it is more specifically a foo-bar". Kind of like the difference between an ID (specific) and a class (generic). – Ethan Brown Feb 08 '14 at 20:07
  • Dayumn, that's what I expected. Thank you for trying to slim it down for me! – Jacob Kelley Feb 08 '14 at 20:09