How can I select an element with jQuery by matching a partial attribute? [duplicate]

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.

Answers:

Answer

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"});  
    }
});
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.