Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all elements that don't contain a certain string

Is it possible to select all elements with a certain class, but not if they contain certain .text()?

Here is what I have so far -

<div class="test">0</div>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>

var divList = $(".test").toArray();
var divLength = divList.length;

What I want to do with this code is to not include the <div> with the 0 in it.

like image 999
Rory Standley Avatar asked Nov 20 '12 18:11

Rory Standley


2 Answers

$('.test').not(':contains(0)')

http://api.jquery.com/contains-selector/

Incidentally, to answer epascarello's question, this will match ANY substring ANYWHERE inside the element. If your numbers go up to 10, it will match and discount that one as well. You'll need a custom selector or a .filter() function if that's an issue for you.

like image 191
Blazemonger Avatar answered Sep 28 '22 16:09

Blazemonger


A quick google brought this to the surface http://forum.jquery.com/topic/jquery-opposite-of-contains

It comes down to this

$(".test:not(:contains('0'))")

EDIT

A test by @jbabey shows that the accepted answer is faster, so use that

$(".test").not(":contains(0)");

As a followup on epascarello's answer, the following selector will do an exact match (this is not included in jQuery by default!)

$.expr[":"].econtains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}

To do an exact match, you can now use

$(".test").not(":econtains(0)");​
like image 29
Vespakoen Avatar answered Sep 28 '22 15:09

Vespakoen