Run code when the page is ready
Put your code inside ready() so the elements exist before you use them. Scripts at the end of <body> do not need it.
jQuery · Run code when the page is readyBeginner
$(function () {
// same as $(document).ready(function () { ... });
console.log('DOM is ready');
$('#msg').text('Page loaded');
});readydocumentbasics