Document:getElementsByName() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Document 对象的 getElementsByName() 方法返回文档中具有给定 name 属性的所有元素的 NodeList 集合。

语法

js
getElementsByName(name)

参数

name

我们要查找元素的 name 属性的值。

返回值

一个实时的 NodeList 集合,这意味着当带有相同 name 的新元素被添加到文档中,或从文档中移除时,该集合会自动更新。

示例

html
<!doctype html>
<html lang="en">
  <head>
    <title>示例:使用 document.getElementsByName</title>
  </head>
  <body>
    <input type="hidden" name="up" />
    <input type="hidden" name="down" />
  </body>
</html>
js
const up_names = document.getElementsByName("up");
console.log(up_names[0].tagName); // 显示“INPUT”

备注

name 属性只在(X)HTML 文档中可用。

返回的 NodeList 集合包含了所有具有给定 name 的元素,例如 <meta><object> 甚至包括根本不支持 name 属性的元素。

规范

Specification
HTML
# dom-document-getelementsbyname-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getElementsByName

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
See implementation notes.
Has more compatibility info.

参见