Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving Error Message: "Uncaught TypeError: Cannot read property 'focus' of null" when trying to call focus() to an element ID

I have an element in my DOM where I have attached an ID. I want to call focus on that element after the Page Loads and set it to a css style (border: yellow) to highlight that it's currently focused. This is what I have:

//main.html
  <myElement id= 'myEl'>

//main.js
window.setTimeout(function ()  { 
        document.getElementById('#myEl').focus(); 
    }, 0);

When I refresh the page I receive this error:

Uncaught TypeError: Cannot read property 'focus' of null

like image 906
Kode_12 Avatar asked Mar 08 '16 16:03

Kode_12


2 Answers

That because javascript can't find any element with id='#myEl', remove the extra # in :

document.getElementById('#myEl').focus(); 
_________________________^

Or use jquery selector instead :

$('#myEl').focus(); 
like image 150
Zakaria Acharki Avatar answered Sep 20 '22 23:09

Zakaria Acharki


Component ID changes in runtime, so use a class rather than ID, will work, like

$(".ClassName").focus();
like image 24
tubefavorites.com Avatar answered Sep 21 '22 23:09

tubefavorites.com