Last Updated: May 15, 2019
·
4.989K
· paranoida

Custom jQuery Selectors using Expressions

Overview

Below you can find my code snippets. I always wanted to use something more that standard jq and css selectors (:eq, :first, :last, etc). I've learnt how can I do that and now I share it with you. Many people don't use it because they don't know how.

Cheers.

1 - Simple Expression

// standard approach:
$("span[class*=icon]");

// custom selector:
jQuery.extend(jQuery.expr[':'], {
  icon: function(el) {
    var c = el.className.toLowerCase(); 
    return c.match("icon")
  }
});

// much better
$("span:icon");

2 - Expression + as a function

// standard approach:
$("span[class*=icon][class*=mega]");

// custom selector/function:
jQuery.extend(jQuery.expr[':'], {
  icon: function(el, index, meta) {
    var c = el.className.toLowerCase(); 
    return meta[3] ? ( c.match("icon") && c.match(meta[3])) : c.match("icon")
  }
})

// much better
$("span:icon(mega)");

3 - Expression - debug mode

// debug mode:
jQuery.extend(jQuery.expr[':'], {
  debug: function(el, index, meta) {
    console.log("--- debug ---");
    console.log("element: ", el);
    console.log("index: ", index);
    console.log("meta: ", meta);
    console.log("--- /debug ---");
    return el.nodeName.toLowerCase()==="span";
  }
})

$("span:first:debug");
$("span:first:debug(args)");

4. More Examples

// $("a.button.new-repo").attr("data-button", "new-repo");

jQuery.extend(jQuery.expr[':'], {
  button: function(el, index, meta) {
    return el.nodeName.toLowerCase()==="a"&&el.className.match("button")&&el.dataset.button===meta[3];
  }
});

// much better
$("a:button");
$("a:button(new-repo)");

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside