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?

2
  • can't you add a class "of-interest" to the div that you're interested in?
    – Kaarel
    Oct 12, 2013 at 9:48
  • 1
    @KaarelKont-Kontson I can't change DOM, this is strictly client-side javascript. Oct 12, 2013 at 9:49

3 Answers 3

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

2
  • 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). Oct 12, 2013 at 10:27
  • Good note. I change my answer accordingly.
    – ferdynator
    Oct 12, 2013 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;
}
0
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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.