0

i have linked my script.js file to my index.html file and both files are in same directory. i have linked that script.js file in section but that is not working when i open-up the console it is shwoing

script.js:2 Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

but whenever i link that file in the last part of the section perfectly, even putting that file in the first section of also not working.

inde.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="script.js"></script>
    <meta charset="UTF-8">
    <title>Sample</title>
</head>

<body>

    <p id="name">
        <span>john</span>
    </p>

</body>

</html> 

script.js:

var result = document.getElementById("name");
var final = result.getElementsByTagName("span");
console.log(final);
Dora
  • 3
  • 3
  • 1
    Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Taplar Apr 21 '20 at 17:41
  • When you link javascript files in head, the won't see the dom elements rendered in body, thus your script won't see the `

    `. either put your code in `window.onload` or move it to the footer.

    – rksh1997 Apr 21 '20 at 17:41
  • @Taplar then why in most of the examples they put that script.js file in – Dora Apr 21 '20 at 17:45
  • Scripts can go in the head so long as the logic that tries to find elements in the DOM, happens after the DOM is loaded. – Taplar Apr 21 '20 at 17:48
  • rashad-kokash whenever i put that – Dora Apr 21 '20 at 17:49
  • As covered by the duplicate, the usage of a document ready or a load event handler on the window allows any logic to be put in the head, without having to worry about the DOM being loaded yet, as they delay the execution of the logic until the DOM is loaded. – Taplar Apr 21 '20 at 17:50

1 Answers1

0

Scripts can go in the head so long as the logic that tries to find elements in the DOM, happens after the DOM is loaded.

As covered by the duplicate, the usage of a document ready or a load event handler on the window allows any logic to be put in the head, without having to worry about the DOM being loaded yet, as they delay the execution of the logic until the DOM is loaded.

Thank You @taplar

Dora
  • 3
  • 3