+ 2
Why doesn't javascript work?
When I try to run JavaScript that includes DOM (specifically) in the JavaScript console here on sololearn it doesn't work unless I type in <script> tags in html side. it always says "Cannot return value of null" is there anything I'm doing wrong?
9 Réponses
+ 4
It's because your Javascript code runs before your html is ready/parsed.
Put your javascript code in js tab on sololearn between onload like below it should run fine
<html>..
<p >this is p</p>
..
</html>...
//JS tab on sololearn
this.onload = function(){
var p = document.querySelector('p')
p.innerText = "This text was added with javascript! Hail Javscript!"
}
+ 2
Yeah, you‘re trying to Return a value of null ;)
How and what are you exactly doing?
+ 2
e.g.
HTML -----
...
<div id="d"></div>
...
JS ------
var elem = document.getElementEyId("d");
elem.innerHTML = "example";
👆
Doesn't work
But
👇
HTML ONLY --
...
<div id="d"></div>
...
<script>
var elem = document.getElementEyId("d");
elem.innerHTML = "example";
</script>
+ 2
I understand that and all with the tags and sometimes external with src... but I'm talking about here on sololearn in th js console
+ 2
then how can I ensure that it runs after the html has run? Should I only write in the script tags in the html side or is there something I need to specify in the code?