我试图从用户生成的文本框的有序列表中选择输入框的值,然后将其值记录到控制台。我还没有找到选择ID未知的孩子的child元素的值的方法。目前,我不断收到此控制台错误:

cannot read property 'getElementsByTagName' of undefined


这是我的HTML:

<form id="form1" action="processing.php" method="post">
    <ol id="spawnList">
    </ol>
    <button type="button" id="spawnbtn" onClick="spawnSilly();">Add</button>
    <button type="button" name="submit" onClick="sub_strings()">Save</button>
</form>


这是用户将生成的示例列表元素:

<li id="465817232" class="1" index="1">
    <input type="text" placeholder="Title" id="465817232" class="1" index="1">
    <button type="button" onclick="redirect()" id="465817232" class="1" index="1">Edit</button>
    <button id="465817232" onclick="removeElement(this.id)" class="1" index="1">Delete</button>
</li>


这是我的JS函数:

    function sub_strings()
    {
        var printer = document.getElementById("spawnList").getElementsByTagName["LI"].getElementsByTagName["INPUT"].item[1];
        console.log(printer)
    }


任何帮助将不胜感激:)

最佳答案

可能您在考虑元素中的那些属性是数组,但是,那些“属性”是返回“数组”的函数(实际上是返回可以被视为数组的对象)。

我建议您使用使用选择器的.querySelector和/或.querySelectorAll之类的功能。



Array.from(document.querySelectorAll('#spawnList li input')).forEach(input => {
  console.log(input.id);
});

<form id="form1" action="processing.php" method="post">
  <ol id="spawnList">
    <li id="465817232" class="1" index="1">
      <input type="text" placeholder="Title" id="465817232" class="1" index="1">
      <button type="button" onclick="redirect()" id="465817232" class="1" index="1">Edit</button>
      <button id="465817232" onclick="removeElement(this.id)" class="1" index="1">Delete</button>
    </li>
  </ol>
  <button type="button" id="spawnbtn" onClick="spawnSilly();">Add</button>
  <button type="button" name="submit" onClick="sub_strings()">Save</button>
</form>

关于javascript - 如何记录嵌套的输入元素值而不需要其ID?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55860098/

10-11 22:27
查看更多