Reputation: 625
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/
Upvotes: 19
Views: 6718
Reputation: 1724
Inline scripts are always run as they are parsed and the < script > tag only sees what above of him. Best solution on pure JS:
<input type="text"/> <!-- The element I want to select -->
<script>
var inputs = document.querySelectorAll('input');
var above_input = inputs[inputs.length - 1];
</script>
<input type="text"/>
Upvotes: 0
Reputation: 6114
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();
Upvotes: 9
Reputation: 9336
Native DOM solution:
var all = document.getElementsByTagName("*");
var input = all[all.length - 2];
The script
will be the last element on the page when it runs, so the input
will be second to last.
Upvotes: -1
Reputation: 4257
Here's a jsfiddle showing my solution.
$("input:last").val("test");
This works because when the script is reached, the input immediately preceding it is the last input to be created - the following <input>
's have not yet been added to the DOM. If you ran the code after page load (that is, in an onload
even handler), this wouldn't work.
It's worth noting that I would personally prefer ids, so that you don't rely on inline JavaScript (which is usually a bad idea).
Upvotes: 4