Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the last div based on attribute

I have this html code:

<div id="mydiv">
    [other divs]
    <div data-day="1">content</div>
    [other divs with data-day attribute]
    <div data-day="random">content</div>
    [other divs]
</div>

I wanna select the last element in the mydiv that has data-day attribute. How can I do this?

#mydiv div[data-day]:last-child

I tried this, but it didn't work.

like image 275
klenium Avatar asked Dec 28 '13 16:12

klenium


2 Answers

There is no real css-only solution to your question. With Javascript you could do this, I guess.

  • last-child doesn't work, because it only works for the last element of its parent.
    In your case: Only if it was the last element with no other element following it.
  • last-of-type doesn't work, because it only selects by types, not attributes or classes.

Workaround:

Add a class to the last element with a certain attribute by hand:

<div id="mydiv">
    <div></div>
    <div data-day="1">content</div>
    <div></div>
    <div data-day="random" class="last-data-day">content</div>
    <div></div>
</div>
like image 187
kleinfreund Avatar answered Sep 20 '22 16:09

kleinfreund


I have done a quick google search and found the following links useful:

CSS Tricks

Stack Overflow (User with same issue)

The answer is:

:last-child only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type

http://jsfiddle.net/C23g6/3/

like image 42
AaronHatton Avatar answered Sep 23 '22 16:09

AaronHatton