Channing Wang
Channing Wang

Reputation: 1

why return document.getElementById doesn't work

var $ = function (id){return document.getElementById(id);}
 window.onload=function(){
 $("num").onfocus=function(){
        $("show").style.display="block";
 }

Uncaught TypeError: undefined is not a function

but when i change $("num") to $("#num") it can works ,why?

Upvotes: 0

Views: 194

Answers (3)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

You're most probably referencing uninformative jQuery $ variable name. And the reason is that both window.jQuery and window.$ are pointing to jQuery instance in case of referencing jQuery framework (sources).


In fact, next should work as expected:

 window.onload=function(){
   var $ = function (id){return document.getElementById(id);} 
   $("num").onfocus=function(){
        $("show").style.display="block";
   }
 }

Upvotes: 0

mplungjan
mplungjan

Reputation: 177950

Your code works if you

a) do not have jQuery loaded

b) add the missing curly bracket

Live demo

var $ = function (id){return document.getElementById(id);} 

window.onload=function(){
   $("num").onfocus=function(){
        $("show").style.display="block";
   }       
 }

Upvotes: 2

DARK_DUCK
DARK_DUCK

Reputation: 1777

You must have jQuery loaded on your page, and you define $ as a local variable, so during the onload the $ variable take it's old signification which is jQuery. And jQuery uses the same selectors as CSS.

You can solve your problem by disabling jQuery if you don't need it, or setting it in compatibility mode, or setting your $ variable as global variable.

Upvotes: 2

Related Questions