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

Viewed 56332

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

3 Answers

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