Skip to content
Advertisement

variable (element).style is undefined

    <textarea id="textarea" rows="10" cols="50" maxlength="10"></textarea>
    <span id="counter">10</span>
    <script>
        let textArea=document.getElementById('textarea'),
        counter=document.getElementById('counter'),
        number=counter.innerHTML;
        textArea.oninput=function(){
        counter.innerHTML=number-textArea.value.length;
        if(number==0){
            number.style.color="red";//number.style is undefined
        }else{
            number.style.color="black";
        }
    }
    </script>

why it says variable (element).style is undefined? I tried .style.color=”red”; on a different code & it works!

Advertisement

Answer

  • First you have to compare against counter.innerHTML because you update its value.
    The value of counter doesn’t change and will all the time be 10 as you can see in the snippet below.

  • Second the value of number is counter.innerHTML;


number=counter.innerHTML;

This means that is does not have a style.color property instead you should set the style.color of your counter element.

<textarea id="textarea" rows="10" cols="50" maxlength="10"></textarea>
    <span id="counter">10</span>
    <script>
        let textArea=document.getElementById('textarea'),
        counter=document.getElementById('counter'),
        number=counter.innerHTML;
        textArea.oninput=function(){
        counter.innerHTML=number-textArea.value.length;
        if(counter.innerHTML==0){
            counter.style.color="red";//number.style is undefined
        }else{
            counter.style.color="black";
        }
    }
    </script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement