+ 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
7 odpowiedzi
+ 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.
+ 13
Change
var a = document.hetElementById("ID")
to
var a = document.getElementById("ID")
And, add semicolons.
+ 10
Thank You All
+ 8
@Krishna Sir It Was a Type Mistake In My Question
https://code.sololearn.com/WF9VacH8b5OJ/?ref=app
+ 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");
}
+ 3
first line : getElementById("ID");// get + semicolon
inside the function:
missing semicolon at the end
+ 1
I suggest using ; JavaScript is strongly typed