tags:

views:

23

answers:

3

I need to determine which element comes first in my markup, such as an input or select. For example

<body>
    <input type="text" />
    <select><option>Test</option></select>
<body>

In this case, the input comes first in the DOM whereas

<body>
    <select><option>Test</option></select>
    <input type="text" />
<body>

in this case, select comes first. Any way to do this using jQuery? Thanks

EDIT: Just to clarify, I don't want the very first element, I ONLY want to know if between the input and select element, which comes first. There could be other elements before the select and input elements.

+1  A: 

If you want the very first element in the <body>, you can use :first-child like this:

$("body > :first-child")

For example your in first example:

alert($("body > :first-child")[0].nodeName);​ //alerts "INPUT"

You can give it a try here


Or to get the first input type, you can do this:

$(":input:first")

for example:

alert($(":input:first")[0].nodeName);​ //alerts "INPUT"

You can try that version here

Nick Craver
I don't want the very first element, I want to know if between the input and select element, which comes first
Axsuul
@Axsuul - Updated to only look at input type elements :)
Nick Craver
@Gert - That would find *any* first child at any level, so it'd select lots of elements :)
Nick Craver
Perhaps not relevant to the situation, but if there happens to be a `textarea` earlier on the page, `:input` would select that.
patrick dw
@patrick - True, I think we're missing a lot of information though, e.g. how to identify these elements, do they not have names or anything? It seems unlikely the parameters given in the question are the *only* requirements here.
Nick Craver
Nick - Agreed. Not much to go on here. Just noting that there's a possible (though perhaps remote) chance of failure with `:input`.
patrick dw
+1  A: 

Use index. if $('select:first').index() < $('input:first').index() then the select is first

See a sample here: http://jsfiddle.net/ZLmMB/

Adam
Thanks, this was exactly what I was looking for
Axsuul
This would work as long as the first `select` and `input` are siblings. If not, `.index()` wouldn't be a reliable indicator.
patrick dw
+1  A: 

If you just want to know which comes first in the entire document, you could do this:

Try it out: http://jsfiddle.net/85zUZ/ Change the order then click Run at the top.

var theFirst = $('input,select').first()[0].tagName;

alert( theFirst );

jQuery returns elements in the order they appear in the DOM, so .first() will grab the first one in order of appearance.

patrick dw