+ 11

Why Its Not Work ???

var a = document.getElementById("ID"); //onclick Event Function function g() { a.style.color = "blue" } https://code.sololearn.com/WF9VacH8b5OJ/?ref=app

23rd May 2017, 1:53 PM
Kailash Loncha
Kailash Loncha - avatar
7 Respuestas
+ 7
First declare( a ) as a global variable and put the document.getElementById("ID"); inside window.onload function . Like this - var a; window.onload=function(){ a=document.getElementById("ID"); } //rest of the code same function g(){ a.style.color="blue"; } Whats happening here is that JavaScript is loaded before HTML is loaded , so getting element by id can't find any object as it hasn't been loaded yet . So window.onload is an event which occurs when the HTML is fully loaded so everything works fine then.
23rd May 2017, 2:32 PM
Utkαrsh
Utkαrsh - avatar
+ 13
Change var a = document.hetElementById("ID") to var a = document.getElementById("ID") And, add semicolons.
23rd May 2017, 2:00 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 10
Thank You All
23rd May 2017, 2:44 PM
Kailash Loncha
Kailash Loncha - avatar
+ 8
@Krishna Sir It Was a Type Mistake In My Question https://code.sololearn.com/WF9VacH8b5OJ/?ref=app
23rd May 2017, 2:08 PM
Kailash Loncha
Kailash Loncha - avatar
+ 5
@utkarsh is correct. js is loaded first var a is null because it cannot find any id. use window.onload or <body onload="Load();"> ........ var a; function Load(){ a = document.getElementById("id"); }
23rd May 2017, 2:43 PM
MR Programmer
MR Programmer - avatar
+ 3
first line : getElementById("ID");// get + semicolon inside the function: missing semicolon at the end
23rd May 2017, 2:00 PM
CHMD
CHMD - avatar
+ 1
I suggest using ; JavaScript is strongly typed
23rd May 2017, 2:09 PM
LDK
LDK - avatar