3

I have no problems except when trying to add !important. It just will not take. I need to add it in order to override a font size dynamically.

Here is how I am adjusting the style:

function newFont(newSizeA) {
    var elems = document.getElementsByClassName('a');
    for(i=0; i<elems.length; i++) {
        elems[i].style.fontSize = newSizeA + 'px!important';
    }

}

newFont(20);

With !important it fails, without !important it works.

EDIT: This needs to work back to IE8 so I am hoping there is a cross browser solution that someone knows of.

TylerH
  • 20,799
  • 66
  • 75
  • 101
RON2015
  • 443
  • 3
  • 16

1 Answers1

9

Your CSS won't parse the !important declaration when written that way (it's expecting only legal values for fontSize in the value space, which means numbers, not numbers and a string). Instead, you can write it this way, by setting the style attribute.

This should be supported by IE8 and up, according to QuirksMode and MSDN.

function newFont(newSizeA) {
    var elems = document.getElementsByClassName('a');
    for(i = 0; i < elems.length; i++) {
        elems[i].setAttribute('style', 'font-size:' + newSizeA + 'px' + '!important');
    }

}

newFont(20);
<div class="a">asdf</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • does this work with IE8? i don't have it on my current computer to test – RON2015 Apr 26 '15 at 05:02
  • @RON2015 I believe support for `.setAttribute` was introduced to IE at version 8, so it should work. I don't have IE8 to test, and I'm not sure of a sandbox site that supports IE8 to test on via VM, either. – TylerH Apr 26 '15 at 05:05
  • Nice answer. This is the correct solution; I have deleted mine as incorrect. – elixenide Apr 26 '15 at 05:05
  • elems[i].setAttribute('style', 'font-size:' + newSize + ' !important'); does add the !important in but it still won't override the previous font-size that is set in the stylesheet for some reason – RON2015 Apr 26 '15 at 05:06
  • @RON2015 I can't seem to reproduce that: http://jsfiddle.net/2of7bs4n/ It's overriding the CSS in the JSFiddle there. – TylerH Apr 26 '15 at 05:08
  • that is very frustrating... it works as soon as I cancel the font-size in fire-bug – RON2015 Apr 26 '15 at 05:11
  • @RON2015 Are you using !important in your CSS as well? I would recommend removing that if possible, then you shouldn't need to use `!important` in your JavaScript, either. – TylerH Apr 26 '15 at 05:14
  • 1
    sorry i realized i need to target the first anchor of that class lol... – RON2015 Apr 26 '15 at 05:17