It seems you are making dynamic HTML inside JS code and immediately trying to get the tags you just added. If so, your code will have to wait and continue checking until the browser displays your new HTML and adds nodes to the DOM, then you can request them or do something.
The only way I found work is to use usint setTimeOut and continue checking and then execute your last statement. I create a function below that checks for waiting and checks for a specific condition, and then performs a callback function.
//A function to wait until either times up, or until a pass in "funct" returns "true", which ever occured first. //funct - callback function, to be returned true or false. //done - an optional callback function for notify when waiting is over. //timeout - the amount of time in million-second to wait. //caller - optional string of caller for monitoring if multiple waiting session. function waitToSync(funct, done, timeout, caller) { //This is a hack synchronize to wait until funct() returns true or timeout becomes < 0. caller = caller || ''; if ((funct === undefined) || typeof (funct) != 'function') return; function waiting() { if (!funct()) { var dt = new Date(); console.log(caller + " waiting: " + dt.format('yyyy-mm-dd h:MM:ss')); if ((timeout - 1000) > 0) setTimeout(waiting, 1000); //1 second. else { console.log(caller + ': waitToSync timed out!!!'); document.body.style.cursor = 'default'; } timeout -= 1000; } else { if (done !== undefined && (typeof done === 'function')) done(); } } waiting(); }
Do whatever you need or anything to wait. Then call WaitToSync
$.each(wordList, function(index, word){ newHtml += ' ' + word; if (index == 50) { newHtml += '<div>Some HTML</div>' } }); waitToSync( function wait() { return document.getElementsByClassName("newsitem_text").length > 0; }, function dosomething() { $(".newsitem_text").html(newHtml); }, 10000,
source share