skip to Main Content

So I have this basic structure:

<div class="parentA">
<div class="my special classes">
<!-- stuff -->
</div>
</div>

<div class="parentB">
<div class="my special classes">
<!-- stuff -->
</div>
</div>

How can I strip out the "my special classes" of the parentB div only?

Background. I have added extra classes to the core/blocks in WordPress. I also have custom blocks (eg tabs/accordion) that allow InnerBlocks. If I add core/blocks to these I need to strip out these extra classes.

3

Answers


  1. Do you want to remove the styling of the class, or remove the class selector from the HTML?

    If you want to remove the styling, depending on the complexity of inside the stuff of the second block, you can try

    .parentB > .my_special_class1 {
        background-color: inherit;
    }
    

    If you want to remove the actual selectors, the simplest way would probably be to remove/change them manually (assuming its not generated code). You could also use Javascript, like

    /* Not tested */
    function myFunction() {
      var element = document.getElementById("parentB").forEach( e => e.classList.remove("my_special_class1"));
    } 
    

    jQuery also has a removeClass method that is handy if you are using jQuery.

    https://www.w3schools.com/howto/howto_js_remove_class.asp

    Login or Signup to reply.
  2. let specialClasses = ["1", "2", "3"]
    
    let elements = document.querySelectorAll('.parentB .' + specialClasses.join("")) // get them all 
    
    elements.forEach(el => {
        
        el.classList.remove(...specialClasses)
    })
    
    Login or Signup to reply.
  3. You can select all those elements with .parentA .my.special.classes, .parentB .my.special.classes and then remove those classes for those elements:

    document.querySelectorAll('.parentA .my.special.classes, .parentB .my.special.classes').forEach((el) => {
      el.classList.remove('my', 'special', 'classes')
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search