-2

I have the following html that is generated by SiteCore content management:

<input aria-label="Username is required." class="form" id="Username" name="Username" type="text" value="" aria-required="true">

What I would like to do is replace the above with this:

<input aria-label="Email is required." class="form" id="Email" name="Email" type="text" value="" aria-required="true">

How do I do this with jquery or pure javascript?

Ideally, I would like to replace the html as soon as the document has been loaded.

  • 1
    Possible duplicate of [How to replace DOM element in place using Javascript?](https://stackoverflow.com/questions/843680/how-to-replace-dom-element-in-place-using-javascript) – dayuloli Feb 03 '18 at 16:13

1 Answers1

1

Look at the JQuery .replaceWith() function, which is designed for exactly this purpose: https://api.jquery.com/replaceWith/

You could do something like:

$('#Username').replaceWith( [ new html here ]);

Use the $.ready() function to detect when the document is fully loaded: https://api.jquery.com/jQuery.ready/

$.when( $.ready ).then(function() {
    // Document is ready.
    $('#Username').replaceWith(`
        <input aria-label="Email is required." class="form" id="Email" name="Email" type="text" value="" aria-required="true">
    `);
});

Keep in mind that editing auto-generated HTML after the document is loaded isn't a great idea because it puts the UI out of sync with what the backend expects to exist. You may want to see if there's a way to change the code your generator is spitting out, because this approach is rather brittle.

j6m8
  • 2,261
  • 2
  • 26
  • 34