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.
Use index.
if $('select:first').index() < $('input:first').index()
then the select
is first
See a sample here: http://jsfiddle.net/ZLmMB/
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
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.
精彩评论