如何获取指定名称的HTML标签的所有子元素?
假设我有一个看起来像这样的 <div>
:
<div id=test>
<input name=test1/>
<input name=test2/>
</div>
如果我有一个div元素,如何获取任何名为test1或test2的子元素?我尝试使用:div.getElementsByName('test1')
但是那样行不通吗?
如何获取指定名称的HTML标签的所有子元素?
假设我有一个看起来像这样的 <div>
:
<div id=test>
<input name=test1/>
<input name=test2/>
</div>
如果我有一个div元素,如何获取任何名为test1或test2的子元素?我尝试使用:div.getElementsByName('test1')
但是那样行不通吗?
document.querySelector('input[name="test1"]')
或者如果您想要定位特定元素的特定子元素:
var test = document.querySelector('#test')
var test1 = test.querySelector('input[name="test1"]');
window.console.log(test1)
选项 #1:
var x = document.getElementsByName("test1");
选项 #2:
var x = document.querySelectorAll("input[name='test1']");
不起作用是因为getElementsByName是文档对象的方法,您只能调用document.getElementsByName('elementName')。div.getElementsByName('test1')
<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 anid
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 adiv
.
如果您想获取任何具有包含部分匹配值的标签,请使用带有属性选择器和子字符串匹配的querySelectorAll
。
var tags = document.querySelectorAll('*[name*="test"]');
console.log(tags);