0
Follow
4
View

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

dw0620 注册会员
2023-01-26 09:32

If you just want the input background to change color while it's focused. You can achieve this by using CSS selectors. No need for JS

input[type=text]:focus {
  background-color: red;
}

Or if you want the form background to change

form:focus-within {
  background-color:red;
}
poppo13422 注册会员
2023-01-26 09:32

The issue is with this line:

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

First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"]:

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

form.addEventListener('click', () => {
  form.style.backgroundColor = 'green'
});

Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout, focusin and maybe blur events - but better still, you can use CSS:

form input[type="text"]:focus {
  background-color: green;
}
c26533806 注册会员
2023-01-26 09:32

I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp

tony_nc 注册会员
2023-01-26 09:32

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


About the Author

Question Info

Publish Time
2023-01-26 09:32
Update Time
2023-01-26 09:32