14

I am trying to find a way to select #inner3

 <div id="outer">
      <div id="inner1"> </div>
      <div id="inner2"> </div>
      <div id="inner3"> of interest </div>
      <div id="inner4"> </div>
 </div>

… by counting from last (#inner4) because sometimes #2 isn't present …

 <div id="outer">
      <div id="inner1"> </div>
      <div id="inner2"> of interest </div>
      <div id="inner3"> </div>
 </div>

and there are only 3 items (and so #inner3 becomes #inner2).

Note, #id are for clarity's sake, and not really present in my work.

I'm right now using body > .. > div:nth-child(3) but counting from top is a problem for me as explained above.

Any solution to this?

laggingreflex
  • 32,948
  • 35
  • 141
  • 196

3 Answers3

20

You should be able to grab your element with

 documentObject.lastChild.previousSibling

where documentObject is your parent.

Edit

Thank you to David Thomas: Even more accurate would be previousElementSibling because it returns an Element and not a text node:

documentObject.lastChild.previousElementSibling

Sources:
W3Schools
developers.mozilla

ferdynator
  • 6,245
  • 3
  • 27
  • 56
  • 3
    Bear in mind that this will, in many cases, return the textNode (the white-space) that exists between the elements. `previousElementSibling` might be more reliable (where it exists). – David Thomas Oct 12 '13 at 10:27
  • Good note. I change my answer accordingly. – ferdynator Oct 12 '13 at 10:29
4

If I undestood you correctly you could count from the end with :nth-last-child():

.outer *:nth-last-child(2){
  color: green;
}
idmean
  • 14,540
  • 9
  • 54
  • 83
2

The text node can be a problem in both lastChild and previousSibling This worked for me:

documentObject.lastElementChild.previousElementSibling

Found the other part of the solution here: https://stackoverflow.com/a/18341945/8486854

SinunHenkka
  • 445
  • 6
  • 14