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 个子元素


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01