jQuery: filter out elements via class?

后端 未结 3 597
无人共我
无人共我 2020-12-29 06:53

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 \"pea

相关标签:
3条回答
  • 2020-12-29 07:02

    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();
    
    0 讨论(0)
  • 2020-12-29 07:04

    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.

    0 讨论(0)
  • 2020-12-29 07:21

    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 ;)

    0 讨论(0)
提交回复
热议问题