Home > other >  Changing form label (No ID or class) via script
Changing form label (No ID or class) via script

Time:03-12

I have a form in one of my apps:

<div >
    <label>
        Email
        <span ></span>
    </label>
    <input name="email"  type="email" placeholder="Work Email" tabindex="0" value="">
</div>

I have the ability to run a custom script in the header or the body of the page, and I would like to change the label from "Email" to "Company email".

Any suggestions? Thanks

CodePudding user response:

To match an element by its contents you'll need to use XPath.

let emailLabels = document.evaluate( "//div[contains(@class, 'custom-form-field')]/label[contains(., 'Email')]", document, null, XPathResult.ANY_TYPE, null );

let label = emailLabels.iterateNext();

label.innerText = "Company Email";
<div >
    <label>
        Email
        <span ></span>
    </label>
    <input name="email"  type="email" placeholder="Work Email" tabindex="0" value="">
</div>

CodePudding user response:

If you want to use native javascript, can try this:

<div ><label>Email<span ></span></label><input name="email"  type="email" placeholder="Work Email" tabindex="0" value=""></div>
<script>
  custom_field = document.getElementsByClassName('custom-form-field');
  custom_field[0].children[0].outerText = 'Company Email';
</script>

  • Related