Any way to take the previous item?

<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, eg document.getElementById("blah")

.

However, when the page is generated from templates, it is sometimes difficult to make sure the IDs are not repeated. It would be more convenient if I could just link to the first element of a given type (like div or canvas) that lies before the script tag in which this script is included

.

Could this be done somehow or do I need to write additional logic to ensure the divs are unique?

+3


source to share


2 answers


I have to use this:

<div></div>
<script>
    document.currentScript.previousElementSibling.innerHTML = "blah";
</script>

      



currentScript

gets the current script element.

previousElementSibling

gets the previous item.

+2


source


This looks like a job for .prev

$('selector').prev()

      



EDIT: and again without jquery:

var x = document.getElementById("item2").previousSibling.innerHTML;

      

+1


source







All Articles