Q:

How to change HTML between 2 delimiters?

Imagine the following scenario: I have this HTML body (this is just one example, the delimiters will be configurable by 3rd parties, so no way to use DOM methods like getElementBy...) :
<div id="login">
<form method="post" action="https://site.com/login.html?skin=webmail" id="fWM">
<fieldset>
    <p><label>Login<br><input type="text" class="inpText" name="user" id="user"/> </label><span class="provider">@isp.com</span></p>
    <p><label>Password<br><input type="password" class="inpText inpPass" name="pass" id="pass"/></label></p>
</fieldset>
<p id="forgot">
<a href="https://site.com/somelink.html">Forgot password?</a> <span class="pipe">|</span>
<a href="http://site.com/somelink.jhtm">Help</a>
</p>
<br><a><input type="submit" value="" id="bOK"/></a></p>
</form>

Ok, this is just a part of some html body asking for Login and Password. As you can see, I have 
< fieldset > and < /fieldset > and for this example those are my delimiters. This mean, everything between this delimiters I want to change for another html code. I have some 'begin of code' like this to you have some idea about what I'm talking:
var myBody = document.body.innerHTML;
var beginInject = myBody.indexOf("<fieldset>");
var endInject = myBody.indexOf("</fieldset>");
var InjectBody = 'Hello World!';
//what to do now to put Hello World! between the <fieldset> and </fieldset>??

Remember this is just one example, I can need to put the delimiters like < body> and < /body> or something like: "Click Here to Start download" and "Thank you for visiting this website"... What I mean is: can be anything inside the body, and between the 2 delimiters I want to put my HTML code. Thank you.

A:

If you insist to make it your way, use
var beginText = "<p>",
    endText = "</p>",
    injectText = 'Hello World!';

var html = document.body.innerHTML,
    beginPos = html.indexOf(beginText),
    endPos = html.indexOf(endText);

document.body.innerHTML =
    html.substring(0, beginPos + beginText.length)
    +injectText
    +html.substring(endPos + endText.length);

Demo
But be aware that this way

You will remove all event listeners inside your body
You will lose all element's properties (not attributes)
Browser will reload all body (slow)
And it won't work on all cases. For example:

If you search for <p>, you won't match <p class="myClass">
If you search for <p a="b" c="d">, you won't match <p c="d" a="b">
Text could be matched instead of real elements, for example if text appears in a textarea.
endPos could be smaller than beginPos, for example because it appears in a textarea.

The problem is that You can't parse [X]HTML with regex because Zalgo is coming, so it's even worse to parse it with just text.

