Access our premium support and let us know your problems, we will help you solve them.

0
No products in the cart.

Forum Replies Created

Viewing 1 post (of 1 total)
  • Author
    Posts
  • in reply to: Selecting element by data attribute with jQuery #9345
    blankxds
    Participant

    It’s sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):

    $el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();
    

    The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:

    $.expr[":"].hasData = $.expr.createPseudo(function (arg) {
        return function (domEl) {
            var $el = $(domEl);
            return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
        };
    });
    

    Now we can refactor the original statement to something more fluent and readable:

    $el.filter(":hasData('foo-bar')").doSomething();
    
Viewing 1 post (of 1 total)