JavaScript JavaScript and the DOM Getting a Handle on the DOM Selecting by Id

Kim Dallas
Kim Dallas
11,461 Points

What did I miss?

I get stuck with javascript

js/app.js
var button;
var input;

button.addEventListener('click', () => {
  alert(input.value);
}
let input = document.getElementById("phraseText");
let button = document.getElementById("sayPhrase");
console.log (button);
});
index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Phrase Sayer</title>
  </head>
  <body>
    <p><input type="text" id="phraseText"></p>
    <p><button id="sayPhrase">Say Phrase</button></p>
    <script src="js/app.js"></script>
  </body>
</html>

2 Answers

Steven Parker
Steven Parker
155,805 Points

It looks like you have two issues:

  • "button" and "input" are already declared on the top two lines, so don't use "let"
  • you must assign the values before the call to "addEventListener"
Kim Dallas
Kim Dallas
11,461 Points

I don't understand.

Steven Parker
Steven Parker
155,805 Points

Both the "var" and "let" keywords declare variables, so if you say "var button" and then later "let button ...." that's declaring it twice. But you can have "var button" at the top and later assign it "button = ...".

And the code that calls "button.addEventListener..." depends on "button" already having a value, so the assignment must be done before that line instead of after it.

Cheo R
Cheo R
35,541 Points

Since the variables input and button are already declared, you don't need to use let.

Remove the last two lines.