skip to Main Content

I’m fairly new to JavaScript, HTML, and CSS, and while I was making a simple trivia website,and I noticed that when I tried comparing a users input to the expected text input using getElementById, it didn’t work at all, once the code got to the part about comparing inputs, nothing happened. But when I switched it to querySelector, the code worked perfectly. Why is this?

The goal of the code was if the users input matched what the correct answer be, the textbox should become green and text should appear saying "Correct!". If they’re wrong the textbox should turn red and text should say "Incorrect!".

My first code itteration looked like this, which didn’t work.

    let check = document.getElementById("userInput");
        document.querySelector('#submit').addEventListener('click', function() {
            if(check.value == '26')
            {
                check.style.backgroundColor = 'green';
                document.querySelector('#feedback2').innerHTML = 'Correct!';
            }
            else
            {
                check.style.backgroundColor = 'red';
                document.querySelector('#feedback2').innerHTML = 'Incorrect!';
            }
        })

Here is the HTML code that was ran through it:

    <h3>How many innings was the longest baseball game in MLB history</h3>
    <input autocomplete="off" placeholder="Input" id="userInput" type="text">
    <button id="submit">Submit</button>

But when I simply changed "let check" to: "document.querySelector(‘input’);" the code worked as intended. Why did one work over the other?

2

Answers


  1. querySelector returns the first found result which is why you’re getting your input. However, querySelector('input') actually looks for ALL inputs.

    Perhaps you’re missing the id field on your input which is why you can’t find it by searching for the userInput ID.

    Login or Signup to reply.
  2. It seems the issue you’re facing is linked to the timing of those methods. I suggest you to take a look at this answer, to better understand the differences.

    Essentially, you need to know that getElementById() is much faster than querySelector() and that js code runs even if the document is not fully loaded.

    It’s very likely that your js code was executing while the document was being loaded and so getElementById returns null because it couldn’t find the element specified. This problem could be resolved, as you did, by changing getElementById into querySelector, but it is not a fully reliable solution. Instead of that, you should defer your JavaScript or ensure that the thing you are searching is loaded in another way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search