Tom
Tom

Reputation:

jQuery: filter out elements via class?

I have a website featuring a long list of names. To make it more oversee-able, I'd like to put a text link in to

(on load) show all

(on clicking word "pears") hide all elements with class="apple"

(on clicking word "apples") hide all elements with class="pear"

(on clicking "show all") show all

I suppose it'd be like a really simplified version of "as you type" filtering.

Does a plug-in exist for this? I don't even know where to start!

Upvotes: 22

Views: 62213

Answers (4)

user764754
user764754

Reputation: 4236

You can filter out elements via CSS selector with the jQuery not function.

So for instance, to get all elements that aren't pears you can do:

$("*").not(".pear")

Upvotes: 0

Oliver
Oliver

Reputation: 9498

To filter out elements that contain a given class or any other attribute value, using the Attribute Contains Word Selector would be a good solution:

$("span").filter("[class~='apple']")

Actually, for the class attribute, it's even easier to just write:

$("span").filter(".apple") // or:
$("span.apple")

[This is also what Joel Potter wrote in his comment to this answer.]

That way you'll be able to match all of the below:

<span class="apple">...</span>
<span class="apple fruit">...</span>
<span class="fruit apple sweet">...</span>

So whenever you're not 100% sure that you'll only have a single class set on an element, use the ~= operator.

Upvotes: 19

dbf
dbf

Reputation: 3453

Just bumped into this post, I know it's old but to be honest are none of the given answers pretty helpful. In my opinion, you can filter out the elements using the filter with :not, as in filter(':not()').

As Joel Potter stated, using $("span[class='apple']").hide(); will only select the spans with exactly one classname, apple. If multiple classes are present (which is highly likely) then such an approach would not work.

If you click on a word, e.g. pears, you can then filter out the elements that do not contain the class pears.

$('span').show().filter(':not(.pears)').hide();

and you're done ;)

Upvotes: 28

gehsekky
gehsekky

Reputation: 3219

hmm.. if you had a list like the following:

<span class="apple">red apple</span>
<span class="apple">green apple</span>
<span class="pear">big pear</span>
<span class="pear">little pear</span>

the following would show all:

$("span.*").show();

the following would hide all elements with 'class="apple"':

$("span[class='apple']").hide();

or you could go with hiding everything that doesn't have 'class="pear"':

$("span[class!='pear']").hide();

Upvotes: 23

Related Questions