Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing new HTML out to the calling position

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.

like image 614
monksy Avatar asked Sep 28 '11 15:09

monksy


2 Answers

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
like image 91
pimvdb Avatar answered Oct 20 '22 16:10

pimvdb


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].

like image 34
Matthew Abbott Avatar answered Oct 20 '22 14:10

Matthew Abbott