Apply innerHTML to a var
An answer to this question on Stack Overflow.
Question
I was trying to set a variable with innerHTML function But it didn't work. Tried the following code:
error = document.querySelector("#Error").innerHTML;
and
error = document.querySelector("#Error");
and then change what the text. So did this:
btnLogIn.addEventListener("click", function(){
error.innerHTML="Works";
});
Html
<div id="Error"></div>
I know if I apply this document.querySelector("#fontError").innerHTML="Works";
works but I want to avoid this in order to have a better code.
Answer
If you're trying
error = document.querySelector("#Error").innerHTML;
btnLogIn.addEventListener("click", function(){
error.innerHTML="Works";
});
It won't work because error will be holding whatever the value of innerHTML is. The following is definitely the way to go because it will store a reference to the matched object itself:
error = document.querySelector("#Error");
btnLogIn.addEventListener("click", function(){
error.innerHTML="Works";
});
Are you sure that your HTML is correct?
<span id="Error">ERROR TEXT WILL GO HERE</span>