<div id="TheDivIWantTheBelowScriptToAddress"></div>
<script>
    document.getPreviousDiv().innerHTML = "YADDA"
</script>
Now I know that in JS I can easily reference an element by its ID like document.getElementById("blah").
However, when the page is being generated from templates, it sometimes might get tricky to ensure that the ids won't repeat. It would be more convenient if I could just reference the first element of a given type (like div or canvas) that lies before the script tag in which this script is included.
Can this be somehow done or do I have to write extra logic to ensure the uniqueness of divs?
I should use this:
<div></div>
<script>
    document.currentScript.previousElementSibling.innerHTML = "blah";
</script>
The currentScript gets the current script element.
The previousElementSibling gets the previous element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With