Why does jQuery or a DOM method such as getElementById not find the element? Why does jQuery or a DOM method such as getElementById not find the element? jquery jquery

Why does jQuery or a DOM method such as getElementById not find the element?


The element you were trying to find wasn’t in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

<script>  console.log("script #1:", document.getElementById("test")); // null</script><div id="test">test div</div><script>  console.log("script #2:", document.getElementById("test")); // <div id="test" ...</script>