Writing new HTML in a defiant position

How are you going to write HTML to the jQuery function's calling position?

I have an HTML page containing the following jQuery / JS code:

... HTML contents ... <script> functionName(); </script> ... More HTML Contents... 

How can I get a functionName to add / write new content where it is called, and not to select another identifier in the document and then add it.

JavaScript document.write can do this, however, I read that it twists jQuery's ability to work with the DOM later.

+6
source share
2 answers

Inspired by this answer .

The scripts seem to be running in order, so during the call, the last script tag at that very moment is the script tag that contains this 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 
+2
source

It depends on how document.write used. If it is used before the page finishes loading, then it will be fine, but if it is used after (say, called from the page load event), then it will put the document in an exception state ( write calls the document a stream that opens and starts write that either leads to a blank page (in IE), or to an open document that never ends [ document.close , explicitly called by the browser after the page has finished loading).

+1
source

Source: https://habr.com/ru/post/898217/


All Articles