Search code examples
javascriptcssinline-styles

How to set inline CSS of element to default using javascript?


I have simple function in which I change the default styling of text when a checkbox is checked, and change the styling back to default when checkbox gets unchecked.

The terms.style = ""; should reset the style back to default, but for some reasons it doesn't, and I have absolutely no idea why. I know that the else scope is performed when checkbox gets unchecked, as I have tested it with manually entering different style.

const form = document.getElementById('form');
const checkBox = form.querySelector('input[name=termsCheckBox]');

checkBox.addEventListener('click', function(){
    const terms = document.getElementById('termsText');
    if (checkBox.checked){
        terms.style = "color: black; font-weight: normal";
    } else {
        terms.style = "";
    }
});//end of function

Solution

  • You can get inline CSS in style attribute of element using getAttribute() and store it in variable and on check/uncheck of checkbox insert and remove it from style attribute

    var checkBox = document.querySelector('#form input[name=termsCheckBox]'),
        terms = document.getElementById('termsText'),
        style = terms.getAttribute('style');
    
    checkBox.addEventListener('click', function(){
      if (checkBox.checked)
        terms.style.cssText = "color:black; font-weight:normal";
      else
        terms.style.cssText = style;
    });
    <form id="form">
      <input type="checkbox" name="termsCheckBox">
      <textarea id="termsText" style="color:red; font-weight:bold">termsText</textarea>
    </form>