Home > Back-end >  jquery change style class attribute value
jquery change style class attribute value

Time:11-05

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

CodePudding user response:

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 >
  <button data-color="blue">blue</button>
  <button data-color="red">red</button>
  <button data-color="yellow">yellow</button>
</div>

  • Related