How can I select an nth child without knowing the parent element?(如何在不知道父元素的情况下选择第 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-child
、last-child
和 nth-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 个子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不知道父元素的情况下选择第 n 个子元素


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01