Reputation: 2617
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.
Upvotes: 9
Views: 23758
Reputation: 6799
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.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>
Upvotes: 8
Reputation: 392
I have done a quick google search and found the following links useful:
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
Upvotes: 1