简体   繁体   中英

getElementById works only after refreshing the page

I'm Trying to access results div in the results page of google.co.uk. Using firebug one can see that the id of the div is "res" but for some reason getElementById('res') fails. to make things even weirder - if i refresh the page (F5 or ctrl+F5), the function succeeds.

Also, if i look in the source code of the results page i dont see anything that looks like the DOM described in firebug.

Why is this happening and how can i ensure getElementById('res') will succeed with any refresh by the user.

Thanks.

EDIT: im adding aa short code to simplify the problem. after placing a query in google.co.uk the page redirects and the alert 'working' pops but the second alert doesnt. after refreshing, both alerts pop although the second one says 0 which is not right because the div has children according to the firebug DOM.

ps: i also failed to mention that im using greasmonkey

(function() {
alert('working');
var results = document.getElementById('res');
alert(results.childNodes.length);
})();
window.addEventListener("DOMContentLoaded", function () {
    var results = document.getElementById('res');
    alert(results.childNodes.length);
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM