я получаю эту ошибку
error:Uncaught TypeError: Cannot read properties of null (reading 'value')
at HTMLButtonElement.<anonymous> (script.js:6:23)
Вот мой код
const button = document.getElementById('button');
const input = document.querySelector('input[name = "num"]:checked')
button.addEventListener('click', () => {
console.info(input.value)
input.value = document.getElementById('output').innerHTML
let before = document.getElementById('before')
let after = document.getElementById('after')
before.style.display = 'none'
after.style.display = 'flex'
})
Я пытаюсь выполнить задание от Frontend Mentor, мне нужно получить доступ к проверяемому входному значению, и появляется эта ошибка, но я не могу найти решение
извините, я написала Wearg? английский не мой родной язык
null
потому, что querySelector
не нашел подходящего элемента, возможно, потому, что вы слишком рано ищете проверенный ввод (я предполагаю, что при загрузке страницы). Вместо этого выполняйте запрос DOM внутри обработчика click
, чтобы вы смотрели по клику, а не по загрузке страницы.
const button = document.getElementById("button");
button.addEventListener("click", () => {
// Look for the checked input now that the button has been clicked
const input = document.querySelector('input[name = "num"]:checked');
// *** Note the optional chaining (?.) on the below.
// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
// That way, we get `undefined` instead of an error if no element matched
// the selector.
console.info(input?.value);
/*
input.value = document.getElementById("output").innerHTML;
let before = document.getElementById("before");
let after = document.getElementById("after");
before.style.display = "none";
after.style.display = "flex";
*/
});
<input type = "button" id = "button" value = "Click Me">
<label>
<input type = "radio" name = "num" value = "A"> A
</label>
<label>
<input type = "radio" name = "num" value = "B"> B
</label>
how do a do
Почему-то это звучит как фанатичная мелодия для песни.