Javascript – Select the element right before the script tag

javascriptjqueryjquery-selectors

How would you select the first input in the code below without editing the DOM (using jQuery if needed)?

<input type="text"/> <!-- The element I want to select -->
<script>
    // Select the input above
</script>
<input type="text"/>

Please note there is an unknown number of inputs and script tags before and after this code sample, thus solutions like $("input:eq(1)") won't work.

The tricky part is to select the input placed right before the script tag from which the current JavaScript is being executed.

No need to ask me why I want to do this either, that's purely for the beauty of it, I want to do it without having to add random ids to my inputs if that's possible.

Edit
Here's why most of the answers won't work: http://jsfiddle.net/2WqfP/

Best Answer

Scripts are always run as they are loaded, so the <script> tag that's running will always be the last one on the page. With pure JS you can get it like this:

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length - 1];

Edit: I got this wrong before. To get the input at this point, you want to get the preceding sibling, so you'd use previousSibling. Also, see thesystem's comment below about text nodes and a potential solution.

var scripts = document.getElementsByTagName('script'),
    currentScript = scripts[scripts.length - 1],
    input = currentScript.previousSibling;

You could also use jQuery:

var currentScript = $('script').last();

Once you have the script, you can get the preceding input easily:

var input = $('script').last().prev();