PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Make jQuery :contains Case-Insensitive

Make jQuery :contains Case-Insensitive

jQuery.expr[':'].Contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};
jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

With this in place,

$("div:contains('John')")

would select all three of these elements:

<div>john</div>
<div>John</div>
<div>hey hey JOHN hey hey</div>

Demo via Pablo Fortes.

Subscribe to The Thread

  1. Some time ago, I found this snippet somewhere on the net:

    $.extend($.expr[":"], {
    "containsNC": function(elem, i, match, array) {
    return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
    });

    I like it better because with this code you leave the :contains selector himself and have a new :containsNC selector, which is case insensitive.


    $("div:containsNC('John')")

  2. Jimbooooooo

    This is solid and definitely useful, but I can’t agree with overriding the behavior of a core jquery component. It’s much better to make a new selector named “:icontains” or similar and use that.

    Other than that, thanks! Saved me some time.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~