Skip to content Skip to sidebar Skip to footer

Select The Element Right Before The Script Tag

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

Solution 1:

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();

Solution 2:

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).

Solution 3:

Try this:

$("script").prev("input");

Solution 4:

Have you tried something like this?

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

http://api.jquery.com/prev/

Solution 5:

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.

Post a Comment for "Select The Element Right Before The Script Tag"