How do you go about writing out HTML to the calling position of a jQuery function?
I have an HTML page that contains the following jQuery/JS code:
... HTML contents ...
<script>
functionName();
</script>
... More HTML Contents...
How do I get functionName
to append/write out new content where it is called, rather than selecting another ID in the document and appending after.
JavaScript's document.write
can do this, however, I've read that it screws up jQuery's ability to work with the DOM later.
Inspired by this answer.
It appears that scripts are run in order, so at the time of calling, the last script tag at that very moment is the script tag which contains that call.
http://jsfiddle.net/vYPHb/2/
function test() {
// get last script tag at the point of calling - useful case of
// explicitly NOT using '$(document).ready' :)
$("script:last").replaceWith("hacked");
}
HTML:
foo
<script>
test();
</script>
bar
It depends how document.write
is being used. If it is being used before the page has finished loading, then it is fine, but should it be used after (say triggered from the page load event), then it will put the document in an exception state (write
causes the document stream to open and starts writing, which either results in a blank page (in IE), or an open document which never finishes [document.close
is explicitly called by the browser once the page has finished loading].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With