代码之家  ›  专栏  ›  技术社区  ›  axsuul

确定在HTML/DOM中哪个元素排在第一位?

  •  1
  • axsuul  · 技术社区  · 15 年前

    input select

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

    输入 排名第一

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

    在这种情况下, 选择 第一位。使用jQuery有什么方法可以做到这一点吗?谢谢

    编辑:只是澄清一下,我不想要第一个元素,我只想知道在输入和选择元素之间,哪个是第一个。在那之前可能还有其他因素 选择 输入 元素。

    3 回复  |  直到 15 年前
        1
  •  5
  •   Community Mohan Dere    6 年前

    index . $('select:first').index() < $('input:first').index() select 是第一个

    http://jsfiddle.net/ZLmMB/

        2
  •  3
  •   user113716    15 年前

    如果您只想知道在整个文档中哪个是第一位的,您可以这样做:

    http://jsfiddle.net/85zUZ/ 更改顺序,然后单击顶部的“运行”。

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

    jQuery按元素在DOM中出现的顺序返回元素,因此 .first() 将按外观顺序抢先一个。

        3
  •  2
  •   Nick Craver    15 年前

    如果你想要 非常 中的第一个元素 <body> ,您可以使用 :first-child 这样地:

    $("body > :first-child")
    

    例如,在第一个示例中:

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

    You can give it a try here


    或者要获取第一个输入类型,可以执行以下操作:

    $(":input:first")
    

    例如:

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

    You can try that version here