Undistraction
Undistraction

Reputation: 43351

Select elements that don't have any classes containing a string

I would like a jQuery selector that selects any elements that do not have a class containing the string '-text';

For example in the following:

<img class="cow" > 
<img class="monkey" > 
<img class="cow-text" > 
<img class="monkey-text" > 

I would like to select:

<img class="cow" > 
<img class="monkey" >

I know I need to use not, but I'm unsure of the format. The following results in no items being selected:

$('.panel').find('.layer').not('[class*="-text"]');

Upvotes: 4

Views: 90

Answers (3)

m1k1o
m1k1o

Reputation: 2364

Try find all img elements and remove all, that end with -text. And use each for multiple elements. e.g. class="monkey-text"

$("img").not("[class$='-text']").each(function(){
  alert($(this).attr("class"));
});

Second preview shows the string text- at the begin of the string. Just replace $ to at ^ e.g. class="text-monkey"

$("img").not("[class^='text-']").each(function(){
  alert($(this).attr("class"));
});

Upvotes: 0

James
James

Reputation: 82096

If the class always ends with "-text" you should use the EndsWith selector e.g.

panel.find('img').not('[class$="-text"]');

Or

panel.find('img:not([class$="-text"])')

This is a more precise solution, the wildcard selector means classes like some-text-class or -text-class would also be picked up by mistake.

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Try

panel.find('img').not('[class*="-text"]');

Upvotes: 1

Related Questions