How right is it put all the javascript code in the tags of the html file?
Is it considered any better to put all the js code in separate .js files?
I’ve noticed that many sites (including this) have some js code written in html file itself(enclosed in script tags).
And lets say I decided to put all possible javascript code in separate files. Now, will those external files have access to the elements of the elements of the html document.
I mean, lets say I want to create a new <p> element with text everytime a user clicks a button. Will the external javascript file have access to the document elements to allow this?
If you reference the
.jsfile in your HTML, the JavaScript will have access to all the elements on the page. This applies to dynamically created elements as well.It is good practice to have as much JavaScript in external files as possible. There shouldn’t be a reason for having JavaScript code in the page itself.