0

I am trying to learn Javascript selectors. How can I select an input type in JS?

<div id="wrapper">

<input type="text" value="OFF" readonly/>

<button type="button">Click Me</button>

</div>
const buttonElem = document.querySelector('button[type=button]');
const inputElem =  document.querySelector('input[type=text]');
buttonElem.addEventListener('click', () => {
  const oldText = inputElem.value;
    return inputElem.value = oldText === "ON" ? "OFF" : "ON";
});
Roh
  • 13
  • 3
  • 2
    `querySelectorAll` returns a list, if you want only one item use `querySelector` – Konrad Mar 10 '23 at 21:30
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 10 '23 at 21:33
  • I replaced it with just querySelector. it still doesn't seem to work. – Roh Mar 10 '23 at 21:34
  • 1
    You don't have any elements that match `input[type=button]`; you have `button[type=button]`. – mykaf Mar 10 '23 at 21:36
  • Next: I think `return inputElem.value = oldText === "ON" ? "OFF" : "ON";` might work, but what is the point of returning the result of the assignment (which I believe it undefined)? – mykaf Mar 10 '23 at 21:41
  • It still throws me an error. – Roh Mar 10 '23 at 21:44
  • Okay; what's that error say? – mykaf Mar 10 '23 at 21:48
  • @Roh The code you have provided works fine as-is (https://jsfiddle.net/fot3w8Ls/). Please provide a [mre]. – Unmitigated Mar 10 '23 at 21:53
  • It Worked. Thanks for everyone helping. i just had Typo. – Roh Mar 10 '23 at 21:58

0 Answers0