CSS3 获取最后一个元素

2022-01-10 00:00:00 css-selectors css

如何从以下代码中获取最后一个元素 (hr):

<span class="hr"></span></div>

<span class="hr"></span></div>

<span class="hr"></span><!-- 我需要这个--></div></div>

.hr:last-child 不适用于此.

当然,DOM 结构可能更复杂.我只需要获取最后需要的元素.

解决方案

你的问题不太清楚;有几种方法可以从您的示例中获取最后一个 .hr 元素,但您说DOM 结构可能更复杂".为了回答您的问题,您需要提及您可能拥有的 DOM 结构;在某些情况下可能会,在某些情况下则不会.

这是从最后一个 div 中获取 .hr 的一种方法:

div div:last-of-type .hr

这是从外部 div 的最后一个子元素中获取 .hr 的另一种方法:

div :last-child .hr

如果你需要从文档中取出最后一个 .hr 元素,不管它在里面是什么,那么你不能在 CSS 中做到这一点.在 CSS 中,您只能选择层次结构的一个特定级别的第一个、最后一个或第 n 个元素,无论嵌套在什么中,都不能选择某种类型的最后一个元素.

How I can get the last element (hr) from the following code:

<div>
    <div>
        <span class="hr"></span>
    </div>

    <div>
        <span class="hr"></span>
    </div>

    <div>
        <span class="hr"></span> <!-- I need this -->
    </div>
</div>

.hr:last-child doesn't work for this.

Of course, DOM structure could be more complicated. I just need to fetch the last needed element.

解决方案

Your question isn't quite clear; there are several ways to get the last .hr element from your example, but you say "DOM structure could be more complicated." In order to answer your question, you need to mention what possible DOM structures you could have; in some it might be possible, in some it will not be.

Here is one way to get the .hr out of the last div:

div div:last-of-type .hr

Here's another way to get the .hr out of the last child of the outer div:

div :last-child .hr

If you need to get the last .hr element out of the document, regardless of what it's inside, then you can't do that in CSS. In CSS, you can only select the first, last, or nth element at one particular level of the hierarchy, you can't select the last element of some type regardless of what it's nested in.

相关文章