如何用jQuery选择第一个孩子? [英] How to select first child with jQuery?

查看:194
本文介绍了如何用jQuery选择第一个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用第一个子选择器选择这些div中的第一个div(具有 id = div1 的div)?

How do I select the first div in these divs (the one with id=div1) using first child selectors?

<div class="alldivs">
   <div class="onediv" id="div1">
   </div>
   <div class="onediv" id="div2">
   </div>
   <div class="onediv" id="div3">
   </div>
</div>


推荐答案

试用: $( '.onediv')。eq(0)

来自演示:其他示例选择器方法定位第一个 LI 取消 UL

From the demo: Other examples of selectors and methods targeting the first LI unside an UL:


.eq() 方法: $('li')。eq(0)

:eq() 选择器: $('li:eq(0)')

.first() 方法 $('li')。first()

:f irst 选择器: $('li:first')

:第一个孩子 选择器: $('li:first-child')

:lt() 选择器: $('li:lt (1)')

:nth-​​child() 选择器: $('li:nth-​​child(1)')

.eq() Method: $('li').eq(0)
:eq() selector: $('li:eq(0)')
.first() Method $('li').first()
:first selector: $('li:first')
:first-child selector: $('li:first-child')
:lt() selector:$('li:lt(1)')
:nth-child() selector:$('li:nth-child(1)')

jQ + JS:

Array.slice() 方法: $('li')。slice(0,1)

您还可以使用 [i] 来获取JS HTMLel从jQuery el中获取 index 。 (数组)集合,例如:

you can also use [i] to get the JS HTMLelement index out of the jQuery el. (array) collection like eg:

$('li')[0]

现在您已经拥有JS元素表示,您必须使用JS本机方法,例如:

now that you have the JS element representation you have to use JS native methods eg:

$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM

或者可以(不要 - 这是糟糕的设计)将它包装回jQuery对象

or you can (don't - it's bad design) wrap it back into a jQuery object

$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead

这篇关于如何用jQuery选择第一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆