Robin Robin - 4 months ago 10
HTML Question

Replacing document.write()

I am trying to replace the

document.write()
function in Javascript. Not completely sure how to do, as I don't know which element to write the HTML to.

Currently, the code javascript code is inserted to my page using:

<script src="//example.com/file.js" type="text/javascript"></script>


The file contains a
document.write()
function:

document.write('<h2>Testing HTML</h2>Hello');


However, as
document.write()
can't be called asynchronously, I need to figure out another solution. I can not use
getElementsById()
or something like that, because I simply don't know any element on the target website.

I want the HTML code to be inserted exactly on the position that the script tag is.

Any suggestions?

Answer

Try this:

<script src="//example.com/file.js" type="text/javascript" id="myScript"></script>

And in the javascript:

var script = document.getElementById('myScript');
script.outerHTML += '<h2>Testing HTML</h2>Hello';

As you don't have the script ID, try this:

var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];

// Async
setTimeout(function() {
    script.outerHTML += '<h2>Testing HTML</h2>Hello';
}, 2000);
Comments