4

Question : Is there any way to append some css property using jquery without changing/overriding the previous value?

For example : if i want to add !important to all of the color properties applied by my style sheet. Would it be possible to do it with jquery? rather than going through each of the css file and putting a !important in front of every color property?

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
Awais Umar
  • 2,027
  • 3
  • 27
  • 46
  • 1
    Refer this http://stackoverflow.com/questions/2655925/apply-important-css-style-using-jquery?rq=1 – Sridhar R Dec 31 '13 at 07:18
  • @SridharR, thank you for your reply. I have studied it already before opening a question. The link you have provided actually mentions it that you need to put some value of the property first and then adding !important after it. What i want is to append !important where ever there is a color property applied. – Awais Umar Dec 31 '13 at 07:24
  • can you explain us why are you trying to achieve this? – Richa Dec 31 '13 at 07:37
  • 4
    If you "need" `!important` applied to _all_ colour properties in your style sheet you're probably doing something wrong. – nnnnnn Dec 31 '13 at 08:03
  • wouldn't applying !important to all colour have the same effect as applying it to none? – Enermis Dec 31 '13 at 08:40

1 Answers1

3

You can use the all selector ('*') together with each(), to loop through each element and apply the !important rule.

$('*').each(function(){
    var c = $(this).css('color');

    $(this).attr('style', 'color: '+c+' !important;');       
});

But be careful, the attr method will unset any previously set in-line style rules. You need to execute the above solution on top of everything first.

See this jsfiddle demo.

Mark S
  • 3,789
  • 3
  • 19
  • 33
  • this would create an empty color attribute with the !important flag on all elements that did not have a color to begin with.. shouldn't you at least check if c isn't empty? – Enermis Dec 31 '13 at 08:41
  • 2
    There is no empty color attribute, if you did not set the `color` the browser will render it with the default `rgb(0, 0, 0)`, even up to the `html` level. So you cannot just check `if(c == '')` but rather `if(c == 'rgb(0, 0, 0)')`. – Mark S Dec 31 '13 at 09:11