--- title: HTMLInputElement.labels slug: Web/API/HTMLInputElement/labels translation_of: Web/API/HTMLInputElement/labels ---
{{APIRef("DOM")}}

 HTMLInputElement.labels 为只读属性,它返回一个{{domxref("NodeList")}} 实例,绑定当前的{{HTMLElement("input")}} 节点的{{HTMLElement("label")}} 元素。

语法

var labelElements = input.labels;

Return value

 {{domxref("NodeList")}} 包含 <label> 元素和 <input> 元素.

实例

HTML

<label id="label1" for="test">Label 1</label>
<input id="test"/>
<label id="label2" for="test">Label 2</label>

JavaScript

window.addEventListener("DOMContentLoaded", function() {
  const input = document.getElementById("test");
  for(var i = 0; i < input.labels.length; i++) {
    console.log(input.labels[i].textContent); // "Label 1" and "Label 2"
  }
});

{{EmbedLiveSample("Example", "100%", 30)}}

规范

Specification Status Comment
{{SpecName("HTML WHATWG", "forms.html#dom-lfe-labels", "labels")}} {{Spec2("HTML WHATWG")}} No change
{{SpecName("HTML5 W3C", "forms.html#dom-lfe-labels", "labels")}} {{Spec2("HTML5 W3C")}} Initial definition

浏览器兼容

{{Compat("api.HTMLInputElement.labels")}}