I am surprised by all the answers here ...
Try the following:
window.setTimeout(function() { }, 0);
Pay attention to the timeout 0. This is not an arbitrary number ... as I understand it (although my understanding can be a little shaky), there are two javascript event queues - one for macros and one for micro-events. In the "larger" district zone, tasks are stored that update the user interface (and the DOM), while the micro-queue performs operations such as a quick task.
Also, understand that setting a timeout does not guarantee that the code is executing that particular value. What this does is essentially put the function in the highest order (the one that processes the UI / DOM), and does not start it until the specified time.
This means that setting a timeout of 0 places it in the UI / DOM part of the javascript event queue, which will be executed with the next possible probability.
This means that the DOM is updated with all the previous elements of the queue (for example, inserted via $.append(...); and when your code works, the DOM is fully accessible.
(ps - I found out about this from the "Secrets of the JavaScript Ninja" - a great book: https://www.manning.com/books/secrets-of-the-javascript-ninja )
jleach Jan 27 '17 at 12:02 on 2017-01-27 12:02
source share