通过FOR属性更改标签的文本

时间:2018-03-14 13:59:22

标签: javascript

我想设置标签的文字。不幸的是,数字36将在每次页面刷新时发生变化。

<label for="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" id="rn_TextInput_36_Label" class="rn_Label">TEXT HERE</label>
<input type="text" id="rn_TextInput_36_Incident.CustomFields.c.other_action_taken" name="Incident.CustomFields.c.other_action_taken" class="rn_Text" maxlength="50" required="">

我可以使用以下方式获取ID:

var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');

我怎样才能使用它来设置标签文本,即用JavaScript中的for属性的值来定位标签 - 而不是jQuery

如上所述,该数字每次都会更改,因此我无法使用标签当前具有的rn_TextInput_36_Label的ID值

3 个答案:

答案 0 :(得分:0)

您的元素具有类rn_Label,因此您可以选择它。

var el = documment.querySelector(".rn_Label");

如果您需要更具体,可以添加标记名称和for属性的一部分。

var el = documment.querySelector("label.rn_Label[for^=rn_TextInput_][for$=_Incident.CustomFields.c.other_action_taken]");

所以这个最后一个选择器选择第一个元素:

  • 的标记名称为label
  • 的班级名称为rn_Label
  • for属性以rn_TextInput_
  • 开头
  • for属性以_Incident.CustomFields.c.other_action_taken
  • 结尾

当然,您可以使用querySelectorAll选择符合该条件的网页上的所有元素。

答案 1 :(得分:0)

你可以像这段代码一样工作:

    var input = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0];
if(input.labels.length > 0) {
    var labelID = input.labels[0].id;
    document.getElementById(labelID ).innerHTML = 'New Text for this lable';
}
else {
     alert('there is no label for this input');
}

https://jsfiddle.net/SETha/75/

答案 2 :(得分:-1)

var id = document.getElementsByName('Incident.CustomFields.c.other_action_taken')[0].getAttribute('id');
document.querySelector("label[for='"+id+"']").innerText = 'new text';

获取ID,然后使用querySelector获取相关标签并设置innertext

相关问题