9

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.

nima
  • 7,796
  • 12
  • 36
  • 53
klenium
  • 2,468
  • 2
  • 24
  • 47
  • 1
    Yeah, I suspected, but I wanted to know if I can use only CSS, no JS or unique class/id. It would be nice if there were a :last selector, like in JQuery. – klenium Dec 28 '13 at 16:39
  • If you know the value of data-day, then #mydiv[data-day="random"];else [data-day]:last-child{css;} work for css3 browsers – cox Dec 28 '13 at 17:03

2 Answers2

8

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>
kleinfreund
  • 6,546
  • 4
  • 30
  • 60
1

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/

Community
  • 1
  • 1
AaronHatton
  • 392
  • 1
  • 7
  • 26
  • 3
    `:last-of-type` won't work here because they're all of the same type (divs). – myajouri Dec 28 '13 at 16:20
  • ^ i concur. It appears the `type` is limited only to `element` types specifically and not sub-selectors. A quick fork of that fiddle shows this very easily http://jsfiddle.net/qnQsL/ – Deryck Dec 28 '13 at 16:30
  • @Deryck Exactly. `last-of-type` only works for _types_, not classes, attributes etc. – kleinfreund Dec 28 '13 at 16:31