1

I want to select all elements with any data attribute in jQuery. Is this possible? I know how to use wildcards in attribute values in the selector, but I can't find a way to use wildcards in the attribute name.

I can't use .data() for this because it also matches other objects like the window. I only want to select elements with a data attribute in the HTML.

raddevon
  • 3,290
  • 4
  • 39
  • 49
  • Note however that psudoclasses are not recommended due to the fact that if you combine it with any other selector, the selector can no longer be handled by `document.querySelectorAll`. I'd suggest using the same solution, but with .filter() instead. – Kevin B Feb 12 '14 at 16:37

1 Answers1

1

Try this

var $result = $('*').filter(function(){
    return !$.isEmptyObject($(this).data());
});

or if you're just talking about the attribute:

var $result = $('*').filter(function(){

    var ret = false;

    $.each(this.attributes, function() {

        if(/^data-/.test(this.nodeName)){
           ret = true;
           return false; //to break the loop
        }
    });

    return ret;
});

Perhaps not the most efficent way, but hey

http://jsfiddle.net/M5bAY/

Johan
  • 35,120
  • 54
  • 178
  • 293
  • 2
    This will also catch elements that have data but no data attributes, fyi. may or may not be a problem for the OP – Kevin B Feb 12 '14 at 16:37
  • 1
    @KevinB I'm aware of that. I wasn't sure if that's what OP wanted. But I'll update with an attribute-only solution as well. – Johan Feb 12 '14 at 16:39