jQuery Remove CSS Class from all Descendants at once

后端 未结 4 1085
花落未央
花落未央 2021-02-13 13:48

Can I remove a specific CSS class from all XYZ elements within an element at once?

Example: Remove CSS class active from all

相关标签:
4条回答
  • 2021-02-13 14:29
    $("#mydiv a").removeClass("active");
    
    0 讨论(0)
  • 2021-02-13 14:32

    If search is a class:

    $("div.search a").removeClass("active");
    

    If search is an ID:

    $("#search a").removeClass("active");
    
    0 讨论(0)
  • 2021-02-13 14:48

    Yeah. You do it like this:

    $("div a .className").removeClass("className")
    

    Or, supposing you only want to do it on a certain div, as long as the div has an id attribute set, you could do this:

    $("#divIDValue a .className").removeClass("className")
    

    With jQuery selectors, # with some text after it refers to the object (div, span, anchor, whatever) with the id attribute set to whatever that text is. A period refers to all objects with that the class name matching the text coming after the period. As demonstrated above, you can nest the selector text. So in the examples above, here's what happens:

    Example #1

    1. Find all divs
    2. Finds all anchors within all divs
    3. Finds all of the anchors from #2 that have class .className

    Example #2

    1. Find the div with the id attribute set to "divIDValue"
    2. Find all anchor tags within that div
    3. Find all anchor tags within that list of anchor tags that match the class name className

    Keep in mind that for all of the objects in your page, only one object can have any particular id value. So, you can have two objects with the id set to 'divIDValue' - although your page will still probably look OK, jQuery will only find the first item with id. Classes, on the other hand, can be used for multiple items (as you probably already know).

    0 讨论(0)
  • 2021-02-13 14:53

    A more generic solution to remove the class from any possible element.

    // I like to use find as I usually have my wrapper in a variable.
    $('#my-wrapper').find('.active').removeClass('active');
    

    Or

    $('#my-wrapper .active').removeClass('active');
    

    This will affect all elements within the wrapper: span, h3, div, li, td, etc. With html 5 there are now over 100 possible tags.

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