At what point in loading can I use document.querySelector(":target")
?
Given the HTML:
<div id="target"></div>
<script src="code.js"></script>
The URL is loaded as http://example.com/page.html#target
And the script is:
console.log(document.querySelector(":target")); // null
window.addEventListener("DOMContentLoaded", e=>{
console.log(document.querySelector(":target")); // null
});
setTimeout(()=>{
console.log(document.querySelector(":target")); // HTMLDivElement#target
},10);
When am I allowed to access :target
? My workaround is document.querySelector(location.hash)
which I guess works but feels silly.