当CSS选择器匹配N个元素时,如何只得到某个索引处的那个?

When a CSS selector matches N elements, how to get only the one at a certain index?

这是我所在的位置:

// Running this CSS selector:
$(".contact-form form")

// Returns this:
// [form, form]

我只想获得这些表格中的第一个,或者可能只是第二个。

我尝试使用一些 CSS 伪选择器,但没有任何效果:

$(".contact-form form:first-of-type")
// [form, form]

$(".contact-form form:nth-of-type(1)")
// [form, form]

我也试过在 .contact-form 而不是 form 上使用这些伪选择器:

$(".contact-form")
// [div.modal-inner.contact-form, div.modal-inner.contact-form]

$(".contact-form:first-of-type")
// [div.modal-inner.contact-form, div.modal-inner.contact-form]

$(".contact-form:nth-of-type(1)")
// [div.modal-inner.contact-form, div.modal-inner.contact-form]

我知道我可以使用数组索引来获取第一个或第二个,但我希望有一种方法可以仅使用 CSS 选择器来实现。这是因为我有一个现有的 API 接受 CSS 选择器的输入,但不处理其他 jQuery 指令。

您可以使用 .get() 方法,如文档所述:

Retrieve one of the elements matched by the jQuery object.

$(".contact-form form").get(0)

这为您提供了 DOM 元素。相反,如果您想要一个 jQuery 对象,则使用 .eq():

Reduce the set of matched elements to the one at the specified index.

$(".contact-form form").eq(0)

所以这实际上等同于:

$($(".contact-form form").get(0))

对此没有纯粹的 CSS 解决方案,但是 jQuery 有 its own extension of selectors and supports things like :eq(n), :gt(n), :lt(n), :first, :last, :even, :odd,...

I have an existing API that accepts input for the CSS selector, but doesn't process other jQuery instructions.

如果通过 CSS 选择器你的意思是你可以传递一个字符串,也许你可以使用 :eq() 选择器,它比 .eq() 慢,因为它是一个 jQuery 选择器(不是 CSS 伪选择器) 必须由 Sizzle 选择器库解析,但它做同样的事情。

$(".contact-form form:eq(0)")