最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Receiving Error Message: "Uncaught TypeError: Cannot read property 'focus' of null&quo

programmeradmin1浏览0评论

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

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

Share Improve this question edited Mar 8, 2016 at 17:03 Zakaria Acharki 67.5k15 gold badges78 silver badges105 bronze badges asked Mar 8, 2016 at 16:53 Kode_12Kode_12 4,79813 gold badges56 silver badges108 bronze badges 2
  • 1 The id value is "myEl", not "#myEl". You don't need the "#" when using getElementById(). – Pointy Commented Mar 8, 2016 at 16:55
  • Why are you using raw javascript if you have access to jQuery? – Erik Philips Commented Mar 8, 2016 at 17:00
Add a comment  | 

3 Answers 3

Reset to default 11

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(); 

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

$(".ClassName").focus();

Below working code for example reference

template code

<div class="css-description">description</div>

script code

this.$nextTick(() => {
   $(".css-description").focus();
})

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论