+ 2
How do you use javascript, when i try to use it it does'nt exist
please help me!!
3 Réponses
+ 3
If you're in sololearn code playground context, the JS code in the JS tab is called in <head> part of Html source/tab, so document is not ready at runtime: you should wrap the JS code requiring access to any document element inside a function called only when document ready (through body/window 'load' event, or document 'DOMContentLoaded'...
In the JS tab, this code will fail:
var body = document.getElementsByTagName('body')[0];
... as it will return null.
But this one works well:
window.onload = function() {
var body = document.getElementsByTagName('body')[0];
}
Anyway, be careful of wich variable scope you're used to declare your variables, if you want to access them from anywhere... Previous 'body' variable will be only accessible to function declared inside the same (anonymous) scope:
window.onload = function() {
var body = document.getElementsByTagName('body')[0];
global_test(); // undefined
local_test(); // HTMLBodyElement
function local_test() {
console.log(body+''); // undefined
}
}
function global_test() {
console.log(body+''); // undefined
}
+ 2
You can embedd it in HTML for example.
+ 1
thanks