I’m looking for a way to change the style of an element, (like the <body>
) when not just text, but specific text like "example" or something is entered in an <input>
. With my current code, a Uncaught TypeError: Cannot set properties of undefined (setting ‘innerText’) gets thrown. How can I fix it? The error is on line 3.
HTML CSS JS
const inputField = document.getElementsByClassName("doSomething");
if(inputField[0].innerText = "5214") {
document.getElementsByTagName("body").style.backgroundColor = "lime";
}
input {
background-color: #ffffff;
}
<label>Numbers only:</label><input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />
<br>
<label>Numbers and decimal points only:</label>
<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />
2
Answers
There are many problems to address in that code.
doSomething
in your javascript. Thus, there are currently NO elements of classdoSomething
, which is whydocument.getElementsByClassName("doSomething")
returnsundefined
.inputField[0].innerText = "5214"
, you are not comparing both values to check if they are equal. You are assigning. Wrong operator. For comparison, you need to use==
.innerText
property, since they don’t work like text elements. Instead, you need to usevalue
.onkeypress
. You must instead call a function containing your code.document.getElementsByTagName("body")
would return an array, not the only body element you have, because you could have many. So, presuming you only have one body tag, you could dodocument.getElementsByTagName("body")[0]
.keyup
, notkeypress
, because the value doesn’t change before thekeypress
. It only does that beforekeyup
. So you are checking the previous value withkeypress
, not the current. Therefore, you must useonkeyup
.document.getElementsByTagName("body")[0].style
, as long as you have only one body tag (which you should), you should instead saydocument.body.style
. Obviously, the second one is easier, simpler and makes more sense than the first.Here is the final code which works:
First of all the class doSomething is missing in your inputs and for body selector
add [0] index for it then your code will run successfully…
as give below of my code.
Html Code
Javascript Code