Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second last child without jquery

Tags:

javascript

dom

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?

like image 452
laggingreflex Avatar asked Oct 12 '13 09:10

laggingreflex


1 Answers

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

like image 143
ferdynator Avatar answered Oct 15 '22 01:10

ferdynator