Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - 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!

question from:https://stackoverflow.com/questions/65864104/variable-element-style-is-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...