我正在尝试从用户生成的有序文本框列表中选择输入框的值,并将其值进一步记录到控制台。我一直无法找到一种方法来选择 ID 未知的子元素的值。目前我不断收到此控制台错误:
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/