Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 745
Alex Ivasyuv Avatar asked Sep 18 '10 08:09

Alex Ivasyuv


People also ask

How do I get the last 3 child in CSS?

The :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.

How do I target the last child of a table in CSS?

With <tr> tag In this CSS :last-child example, the last row (ie: the last <tr> tag) will have a yellow background color. All other rows in the table will not be styled by the :last-child selector.

How do you select all but the last element in CSS?

When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.


1 Answers

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.

like image 87
Brian Campbell Avatar answered Oct 07 '22 18:10

Brian Campbell