Parse HTML to modify it
To solve the root of your problem, I suggest you actually modify the source of that HTML. Add your scripts and attributes there instead of creating this voodoo with JS.

Now if this is the only way you could do it (sigh)...

First, jQuery cannot parse full HTML and I think you're aware of that. It's also mentioned in the documentation how it creates jQuery objects for complex markup.


  If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new  element and sets the innerHTML property of the element to the HTML snippet that was passed in.


An alternative way to do it is to just skip all this work and just inject an external script instead. You could look for &lt;/body&gt; or some element in the markup that's guaranteed to always be there, and replace it with markup containing your external script.

var htmlWithInjectedScript = html.replace('&lt;/body&gt;', '&lt;script src="path/to/script.js"&gt;&lt;/script&gt;&lt;/body&gt;');


This way, you don't have to mangle the markup while having a place to run JavaScript in all its glory. This assumes that the markup is actually executed somewhere, not just for show and tell and that your script is in a location that's always available.