document.querySelectorAll 返回的数组长度始终为 0

Length of the array returned by document.querySelectorAll is always 0

function checkFilled() {
  let inputElements = document.querySelectorAll("table .table_element input");
  let outputElement = document.querySelector("#output");
  outputElement.innerHTML = "You entered : ";
  console.log(inputElements.length);

  for (let [index, inputElement] of inputElements.entries()) {
    outputElement.innerHTML += " " + index + " " + inputElement.value;
    if (inputElement.value == "") {
      inputElement.style = "background-color: red;";
    } else {
      inputElement.style = "background-color: green;";
    }
  }
}
<table class="first">
  <div class="table_element">
    <p style="text-align: center;">First Name :</p>
    <input name="import_date_visit" id="subEmail" type="text" required size="25" oninput="checkFilled();" value="Claudio">
  </div>
  <div class="table_element">
    <p style="text-align: center;">Last name :</p>
    <input name="import_date_visit" type="text" required size="25" oninput="checkFilled();" value="MISSING VALUE">
  </div>
</table>
<p id="output">You entered : nothing yet</p>

每当我在其中一个输入字段中输入任何内容时,0 都会记录到控制台,并且输入不会改变颜色。我确定我遗漏了一些非常明显的东西,但我已经半小时找不到了……

这是因为您的 table 无效 并且浏览器将您的代码解析为(在 devtools 中尝试):

<div class="table_element">
   <p style="text-align: center;">First Name :</p>
   <input name="import_date_visit" id="subEmail" type="text" required="" size="25" oninput="checkFilled();" value="Claudio">
</div>
<div class="table_element">
   <p style="text-align: center;">Last name :</p>
   <input name="import_date_visit" type="text" required="" size="25" oninput="checkFilled();" value="MISSING VALUE">
</div>
<table class="first"></table>

如您所见,table 不再包装您的元素 因为 div 不是它的有效子元素。如果您尝试不使用 table:

的选择器,它会起作用

function checkFilled() {
  let inputElements = document.querySelectorAll(".table_element input");
  let outputElement = document.querySelector("#output");
  outputElement.innerHTML = "You entered : ";
  console.log(inputElements.length);

  for (let [index, inputElement] of inputElements.entries()) {
    outputElement.innerHTML += " " + index + " " + inputElement.value;
    if (inputElement.value == "") {
      inputElement.style = "background-color: red;";
    } else {
      inputElement.style = "background-color: green;";
    }
  }
}
<table class="first">
  <div class="table_element">
    <p style="text-align: center;">First Name :</p>
    <input name="import_date_visit" id="subEmail" type="text" required size="25" oninput="checkFilled();" value="Claudio">
  </div>
  <div class="table_element">
    <p style="text-align: center;">Last name :</p>
    <input name="import_date_visit" type="text" required size="25" oninput="checkFilled();" value="MISSING VALUE">
  </div>
</table>
<p id="output">You entered : nothing yet</p>

您尝试 select 作为 table document.querySelectorAll("table .table_element input"); 的子项的输入,但是有 none。从 selector 中删除“table”,它按预期工作 document.querySelectorAll(".table_element input");