Remove width and height from svg using javascript

I have the following block of code (I remove the path from the svg so don’t mind that)

<div class="c-svg">
    <svg xmlns="http://www.w3.org/2000/svg" class="ie-svg" viewBox="0 0 20 20" width="35" height="35" data-name="Layer 1"><path></svg>
</div>

It has the following classes

.c-svg svg {
    width: 60% !important;
    height: 100% !important;
}

.c-svg svg {
    fill: #fff !important;
    width: 2.5em !important;
    height: 2.5em !important;
}

How would I remove the width and height from these classes. I can’t delete the class unfortunately, but I need to remove the classes, so that when I add a class via JS, I can use them.

It needs to be IE compatable

Answer

If your css weren’t using !important for everything this would be much simpler; normally inline styles override those set externally, so any js-induced changes in style would take precedence over those in the CSS file.

Since you are using !important, you would need to set the inline style to an !important precedence as well (but note this particular method will overwrite any other inline styles already applied to the element):

document.querySelector('.c-svg svg').style.cssText='width: 400px !important'
    .c-svg svg {
        width: 60% !important;
        height: 100% !important;
    }
    
    .c-svg svg {
        fill: #fff !important;
        width: 2.5em !important;
        height: 2.5em !important;
    }
    
    /* Adding so changes are visible: */
    svg {border: 1px solid}
<div class="c-svg">
        <svg xmlns="http://www.w3.org/2000/svg" class="ie-svg" viewBox="0 0 20 20" width="35" height="35" data-name="Layer 1"><path></svg>
    </div>
</div>

Alternatively, you could skip the javascript and add another rule to your CSS with a more specific selector (though it, too, will need to be !important):

.c-svg svg {
  width: 60% !important;
  height: 100% !important;
}

.c-svg svg {
  fill: #fff !important;
  width: 2.5em !important;
  height: 2.5em !important;
}


/* Adding so changes are visible: */
svg {
  border: 1px solid
}

/* override with a more specific selector: */

div.c-svg svg {
  width: 400px !important
}
<div class="c-svg">
  <svg xmlns="http://www.w3.org/2000/svg" class="ie-svg" viewBox="0 0 20 20" width="35" height="35" data-name="Layer 1"><path></svg>
</div>

This is all a pretty good example of why !important should be avoided whenever possible; if you need a rule to override another it’s better to use a more specific selector instead of brute-forcing it with !important.

Leave a Reply

Your email address will not be published. Required fields are marked *