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

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

问题描述

在我不知道父元素的情况下,我无法找到选择第 n 个元素、最后一个元素或第一个元素的方法.nth-child 存在,但仅限于孩子,例如:

<p>一个</p><p>两个</p></div>

p:last-child 选择Two"段落,p:first-child 选择One"段落.但是当我有动态代码并且不知道父级名称是什么,甚至不知道父级到底是什么(可能是 div、span、anchor、ul 等)时呢?

例如:

<你不知道!><p class="select-me">一个</p><p class="select-me">两个</p></你不知道什么!>

如何在这里选择第二段?(我无法选择 youdontknowwhat! 因为我真的不知道它是什么元素(它只是一个假设的名称).

为什么有 first-childlast-childnth-child 选择器而没有 :first, :last, :nth (如 .select-me:first)?

解决方案

:first:first-child 有何不同?每个 HTML 元素都是 DOM 中的某个其他元素的子元素,除了作为根元素的 <html> 之外.– 螺栓时钟

这是因为您不知道父元素.– 福米奇

您不需要知道 :first-child:nth-child() 的父元素即可工作.它们会正常工作,即使你没有指定父元素.

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

.select-me:nth-child(2)

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 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.)?

For example:

<youdontknowwhat!>
   <p class="select-me">One</p>
   <p class="select-me">Two</p>
</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).

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

解决方案

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

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

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.

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天全站免登陆