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:
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 |Uncaught TypeError: Cannot read property 'focus' of null
3 Answers
Reset to default 11That 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();
})
getElementById()
. – Pointy Commented Mar 8, 2016 at 16:55