Changing a label's text by the FOR attribute

pee2pee Source

I would like to set the text of the label. Unfortunately the number 36 will change on each page refresh.

<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="">

I can get the ID by using:

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

How can I then use this to set the label text i.e. target the label by the value of the for attribute in JavaScript - not jQuery

So as mentioned, the number will change each time so I can't use the ID value of rn_TextInput_36_Label that the label currently has



answered 3 months ago user9366559 #1

Your element has the class rn_Label, so you can select by that.

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

If you need to get more specific, you can include the tag name and part of the for attribute.

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

So this last selector selects the first element that:

  • has tag name label
  • has class name rn_Label
  • has a for attribute that starts with rn_TextInput_
  • has a for attribute that ends with _Incident.CustomFields.c.other_action_taken

And of course you can use querySelectorAll to select all elements on the page that meet that criteria.

answered 3 months ago pee2pee #2

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

It gets the ID and then uses querySelector to get the related label and sets the innertext

answered 3 months ago saeid mohammad hashem #3

you can work same as this code:

    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');

comments powered by Disqus