-1

I have style css cur_font class I want to change font-family to 'arial' by jquery and also new font affected on class selectors html,body,h2,h1,div,td


    <style>
    .cur_font html,body,h2,h1,div,td { font-family:'tahoma'; }
    </style>

    <script>
        $(".change_font").on("click", function (e) {
            var font='arial';
            $("style.cur_font").css("font-family",font);
        });
    </script>

trying to change font-family attribute for class cur_font using jquery

sami eisa
  • 29
  • 7
  • You would need to alter the stylesheet cssRules. There is no way to select that in JQuery. There are better ways to do this such as multiple rules or CSS variables. – epascarello Nov 04 '22 at 13:37
  • `$("style.cur_font")` - your style element does not have the class `cur_font`, so this will select nothing. And even if it did, trying to apply a font-family _to_ a `style` element is pointless. – CBroe Nov 04 '22 at 13:37
  • And `.cur_font html` is quite a pointless selector to begin with - there is not element "above" `html`. – CBroe Nov 04 '22 at 13:39
  • I know it's bad , what is the best way to change font for all page html , body div, by jquery – sami eisa Nov 04 '22 at 13:42
  • what about $("html,body,div,td").css("font-family",font); – sami eisa Nov 04 '22 at 13:44
  • 2
    best solution would be multiple classes and you toggle the class. – epascarello Nov 04 '22 at 13:46
  • You can create new style rules and add them to the DOM, eg: https://stackoverflow.com/a/2076345/2181514 (but separate classes then just set the class is the correct way to go (as noted above multiple times). – freedomn-m Nov 04 '22 at 13:48
  • epascarello , what the selector , exmaple please – sami eisa Nov 04 '22 at 13:49

1 Answers1

1

The easiest way to do this would be to toggle a class on the body and apply different styles.

Another approach would be to loop over document.styleSheets and then loop over the cssRules and check to see if the selectorText matches. If it does, modify the rule.

Other option is to use a CSS variable and alter the value of the variable.

document.querySelector(".buttons").addEventListener("click", evt => {
  const btn = evt.target.closest("button");
  if (!btn) return;

  const color = btn.dataset.color;
  document.documentElement.style.setProperty('--myVariable', color);
});
:root {
  --myVariable: red;
}

div {
  background-color: var(--myVariable);
}
<div>Hello World</div>

<div class="buttons">
  <button data-color="blue">blue</button>
  <button data-color="red">red</button>
  <button data-color="yellow">yellow</button>
</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236