如何在不知道父元素的情况下选择第n个孩子? [英] How can I select an nth child without knowing the parent element?

查看:66
本文介绍了如何在不知道父元素的情况下选择第n个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道在不知道父元素的情况下选择第n个元素,最后元素或第一个元素的方法。 nth-child 存在,但仅适用于儿童,例如:

I can't figure out a way of selecting the nth element, last element, or first element in cases where I don't know the parent element. nth-child exists, but only for children, for example:

<div>
   <p>One</p>
   <p>Two</p>
</div>

p:last-child 两个段落,并且 p:first-child 选择One段落。但是,当我有动态代码,不知道父名字是什么,甚至父母真正是什么(可能是一个div,span,anchor,ul等)?

p:last-child selects the "Two" paragraph, and p:first-child selects the "One" paragraph. But what about when I have dynamic code and have no idea what the parent name is, or even what the parent really is (may be a div, span, anchor, ul, etc.)?

例如:

<youdontknowwhat!>
   <p class="select-me">One</p>
   <p class="select-me">Two</p>
</youdontknowwhat!>

如何选择第二段? (我不能选择 youdontknowwhat!,因为我真的不知道它是什么元素(它只是一个假设的名字)。

How do I select the second paragraph here? (I'm unable to select youdontknowwhat! since I really don't know what element it is (it's just a hypothetical name).

为什么第一胎最后一个孩子 nth-child 选择器和NO :first :last :nth (如 .select-me:first )?

Why are there first-child, last-child, and nth-child selectors and NO :first, :last, :nth (like .select-me:first)?

推荐答案


如何:第一不同于:first-child ?每个HTML元素都是DOM中除了< html> 这是根元素的DOM中其他元素的子元素 - BoltClock

How would :first be different from :first-child? Every HTML element is a child of some other element in the DOM except <html> which is the root element. – BoltClock

这是因为你不知道父元素。 - fomicz

It'd be since you don't know the parent element. – fomicz

需要知道:first-child :nth-​​child()的父元素才能工作。

You don't need to know the parent element for :first-child or :nth-child() to work. They will just work, even if you don't specify the parent element.

下面的选择器保证匹配任何适当的 .select-me 元素,无论其父元素是什么:

The following selector is guaranteed to match any appropriate .select-me element regardless of what its parent element is:

.select-me:nth-child(2)

这篇关于如何在不知道父元素的情况下选择第n个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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