How to get nth jQuery element

2019-01-02 17:21发布

In jQuery, $("...").get(3) returns the 3rd DOM element. What is the function to return the 3rd jQuery element?

标签: jquery
11条回答
一个人的天荒地老
2楼-- · 2019-01-02 17:25

Why not browse the (short) selectors page first?

Here it is: the :eq() operator. It is used just like get(), but it returns the jQuery object.

Or you can use .eq() function too.

查看更多
孤独总比滥情好
3楼-- · 2019-01-02 17:25

if you have control over the query which builds the jQuery object, use :eq()

$("div:eq(2)")

If you don't have control over it (for example, it's being passed from another function or something), then use .eq()

var $thirdElement = $jqObj.eq(2);

Or if you want a section of them (say, the third, fourth and fifth elements), use .slice()

var $third4th5thElements = $jqObj.slice(2, 5);
查看更多
孤独总比滥情好
4楼-- · 2019-01-02 17:31

I think you can use this

$("ul li:nth-child(2)").append("<span> - 2nd!</span>");

It finds the second li in each matched ul and notes it.

查看更多
泛滥B
5楼-- · 2019-01-02 17:31

Live Example to access and remove the Nth element with jQuery:

<html>
<head></head>
<body>
    <script type="text/javascript" 
    src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('li:eq(1)').hide();
      });
    </script>
    <ol>
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ol>
</body>
</html>

When it runs, there are two items in the ordered list that show, First, and Third. The second was hidden.

查看更多
零度萤火
6楼-- · 2019-01-02 17:34
 $(function(){
            $(document).find('div').siblings().each(function(){
                var obj = $(this);
                obj.find('div').each(function(){
                    var obj1 = $(this);
                    if(!obj1.children().length > 0){
                        alert(obj1.html());
                    }
                });

            });
        });

<div id="2">
    <div>
        <div>
            <div>XYZ Pvt. Ltd.</div>
        </div>
    </div>
</div>
<div id="3">
    <div>
        <div>
            <div>ABC Pvt Ltd.</div>
        </div>
    </div>
</div>
查看更多
临风纵饮
7楼-- · 2019-01-02 17:39

You can use the :eq selector, for example:

$("td:eq(2)").css("color", "red"); // gets the third td element

Or the Traversing/eq function:

$("td").eq(2).css("color", "red");

Also, remember that the indexes are zero-based.

查看更多
登录 后发表回答