+ 1
Sololearn's web playground broken
The web playground's JavaScript can't access the DOM. I created a div with the id of "test" but the js document.getElementById("test") return null.. it's the same with document.body
3 Respuestas
+ 7
@ValentinHacker suggestion is right... but need some more explanation and acuracy ;P
The JS tab in code playground web project is virtually linked to Html tab (as the Css tab) like it was embeded or linked as external file at the very end of the <head> section... meaning that scripts placed here will be parsed and ran before <body> content was parsed, so DOM isn't still populated with page elements at this (running) time. You need to wait for DOM ready to be accessible, or place your script after the elements you want to access with JS in the Html code...
@Valentin solution is to safely embed all your code in the JS tab (or at least initializations requiring DOM access) inside a function assigned to the 'onload' event of the window/document... (you can also use the 'onload' attribute of <body> tag to call a specific function of your JS tab, but <body> element isn't available at this time, so you cannot assign it dynamically with JS -- only 'window' and 'document' object are available in DOM as soon as start loading/parsing the Html)
Lazy way to do:
window.onload = function() {
/* code */
};
Better way:
window.addEventListener('load',function() {
/* code */
});
Much more efficient and better way:
document.addEventListener('DOMContentLoaded',function() {
/* code */
});
And in all cases, you can assign a named function instead an annonymized one:
function init() {
/* code */
};
window.onload = init;
window.addEventListener('load',init};
document.addEventListener('DOMContentLoaded',init);
+ 17
onload = function() {
//put code here....
};
- 1
Regardez les deux code l'un devient bleu (pourquoi ?)
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
var el = document.getElementsByTagName('a');
el[0].href= 'http://www.sololearn.com';
};
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function(){
var el = documentgetElementsByTagName('a');
el[0].href= 'http://www.sololearn.com';
};