Avatar ·

Correct placement of <script> tags in HTML: where and why?

Hello everyone! I'm a beginner in web development and I can't figure out where to properly insert scripts in an HTML document. In different tutorials I've seen different options: some write scripts in , others at the end of . I've tried both options but run into problems.\n\nHere's an example. I have a simple script that changes the text in a heading:\n\n```javascript\ndocument.getElementById('title').textContent = 'New heading';\n```\n\nIf I insert this script in :\n\n```html\n\n\n\n \n\n\n

Old heading

\n \n\n```\n\nThen an error appears in the browser console: "Cannot read properties of null (reading 'textContent')". But if I move the script to the end of — everything works.\n\nBut I s