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:46

If I understand your question correctly, you can always just wrap the get function like so:

var $someJqueryEl = $($('.myJqueryEls').get(3));
查看更多
与君花间醉酒
3楼-- · 2019-01-02 17:46

If you want to fetch particular element/node or tag in loop for e.g.

<p class="weekday" data-today="monday">Monday</p>
<p class="weekday" data-today="tuesday">Tuesday</p>
<p class="weekday" data-today="wednesday">Wednesday</p>
<p class="weekday" data-today="thursday">Thursday</p>

So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be

$('.weekdays:eq(n)');

e.g.

$('.weekdays:eq(0)');

as well as by other method

$('.weekday').find('p').first('.weekdays').next()/last()/prev();

but first method is more efficient when HTML <tag> has unique class name.

NOTE:Second method is use when their is no class name in target element or node.

for more follow https://api.jquery.com/eq/

查看更多
浪荡孟婆
4楼-- · 2019-01-02 17:48

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}
查看更多
不再属于我。
5楼-- · 2019-01-02 17:49

If you already have the jquery object in a variable, you can also just treat it as a normal indexed array, without the use of jquery:

var all_rows = $("tr");
for(var i=0; i < all_rows.length; i++){
   var row = all_rows[i];
   //additionally, you can use it again in a jquery selector
   $(row).css("background-color","black");
}

Although the above example is not useful in any way, it is representing how you can treat objects created by jquery as indexed arrays.

查看更多
流年柔荑漫光年
6楼-- · 2019-01-02 17:50

.eq() -An integer indicating the 0-based position of the element.

Ex:

Consider a page with a simple list on it:

<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
</ul>

We can apply this method to the set of list items:

$( "li" ).eq( 2 ).css( "background-color", "red" );

For more information : .eq()

查看更多
登录 后发表回答