如何查找具有“ for”属性的标签,该标签指向当前的DIV或文本区域

问题描述

我有两个元素,一个文本区域和一个div,并在每个元素上附加了标签(使用“ for”)。 HTML ::

<textarea  id="txta_1" class="txta" cols="40" rows="3" onkeyup="charCount(this)" ></textarea><br>
<label id="label_1" for="txta_1"></label>

<div id="DIV_1" class="DIV_" contenteditable onkeyup="charCount(this)" >hello</div>
<label id="label_2" for="DIV_1"></label>

Javascript是:

function charCount(th)
{  ("Label element which is attached to it using the FOR").innerHTML = th.value.length; 
}

如何获取具有相应元素“ for”属性的元素? 谢谢,非常感谢

解决方法

如果HTML标签由另一个元素上的“ for”属性引用,则其属性element.labels包含引用标签元素的列表。

请参阅:https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/labels

<label id="label1" for="test">Label 1</label>
<select id="test">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
</select>
<label id="label2" for="test">Label 2</label>

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