How do i change the backgroundcolor of a form element when clicked?

I’ve been trying to figure out how I can change the background color of a form element when it is clicked on.

Heres the code:

<form id="form">

 <input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />

</form>

<script>

</script>

I’m trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.

I’ve tried this, which didn’t work:

<script>
let form = document.queryselector('input type="text"');

form.addEventListener('click', () => {

form.style.backgroundColor = 'green'

});
</script>

I’m very new to coding, so any help is very much appreciated! Thanks!

>Solution :

you should write ('input[type="text"]');

<script>
    let form = document.querySelector('input[type="text"]');

    form.addEventListener("click", () => {
      form.style.backgroundColor = "green";
    });
</script>

Leave a Reply