使用 JavaScript 按名称获取子节点

14

如何获取指定名称的HTML标签的所有子元素?

假设我有一个看起来像这样的 <div>

<div id=test>
    <input name=test1/>
    <input name=test2/>
</div>
如果我有一个div元素,如何获取任何名为test1或test2的子元素?我尝试使用:
div.getElementsByName('test1')

但是那样行不通吗?

4个回答

26

document.querySelector('input[name="test1"]')

或者如果您想要定位特定元素的特定子元素:

var test = document.querySelector('#test')
var test1 = test.querySelector('input[name="test1"]');
window.console.log(test1)

5

选项 #1:

var x = document.getElementsByName("test1");

选项 #2:

var x = document.querySelectorAll("input[name='test1']");

在这两种情况下,您将获得一个数组作为响应:x [0],x [1],...

div.getElementsByName('test1')

不起作用是因为getElementsByName是文档对象的方法,您只能调用document.getElementsByName('elementName')。

3

您的初始代码无法工作,因为您HTML中的name属性没有用引号括起来。它们应该是:

<div id=test>
  <input name="test1" />
  <input name="test2" />
</div>

请注意,getElementsByName 返回匹配元素的实时 NodeList,即使您期望并接收到一个结果,它也是类似数组的对象。

如果您只想获取一个元素而不是包含一个元素的数组,我提供了一些替代方案:

USING THE id ATTRIBUTE: If you know your name will be unique in the whole document, I'd advise using an id instead of the the name or class attributes. Doing so would allow this:

Html:

<div id=test>
  <input id="test1" name="test1"/> 
  <input id="test2" name="test2"/> 
</div>

JavaScript:

document.getElementById("test1");


USING document.querySelector :

If you still need to use the name attribute then you can use document.querySelector with the following selection parameter:

document.querySelector('div > input[name="test1"]')

document.querySelector returns the first element in the document that matches the selection parameter.

In the example above it says, return the first element that is an input with name attribute equal to "test1" that is a child of a div.


1
HTML不需要在属性值周围加引号(这是一个好习惯,但不是必需的)。虽然在这种情况下,他没有在属性值和结束斜杠之间留空格,这是必需的。您似乎也错过了问题;他正在尝试执行div.getElementsByName,但它不起作用(必须是document.getElementsByName)。 - Joshua Davies

0

如果您想获取任何具有包含部分匹配值的标签,请使用带有属性选择器和子字符串匹配的querySelectorAll

var tags = document.querySelectorAll('*[name*="test"]');
console.log(tags);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接