Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

css - CSS3 get last element

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...