JohnOmeg12
JohnOmeg12

Reputation: 1

Changing form label (No ID or class) via script

I have a form in one of my apps:

<div class="custom-form-field">
    <label>
        Email
        <span class="required-asterix"></span>
    </label>
    <input name="email" class="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

Upvotes: 0

Views: 91

Answers (2)

James
James

Reputation: 22247

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 class="custom-form-field">
    <label>
        Email
        <span class="required-asterix"></span>
    </label>
    <input name="email" class="email" type="email" placeholder="Work Email" tabindex="0" value="">
</div>

Upvotes: 1

William Luisan
William Luisan

Reputation: 126

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

<div class="custom-form-field"><label>Email<span class="required-asterix"></span></label><input name="email" class="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>

Upvotes: 0

Related Questions