1

I have a container with several p elements and several input elements. I need to select the last p element inside this container, and for some reason I'm not able to. I've tried several methods but non seem to work. It must be last-child and not nth-child since there might be more elements in the future. Whats the difference between last-of-type and p:last-child?

JSfiddle here.

HTML:

<div id="inputContainer">
    <p class="contact_title">EMAIL</p>
    <p>john@snow</p>
    <p class="contact_title">PHONE</p>
    <p>123-hodor-hodor</p>
    <p class="contact_title">ADDRESS</p>
    <p>castle black</p>
    <input id="name" placeholder="Name">
    <input id="email" type="email" placeholder="Email">
    <input id="phone" type="number" placeholder="Phone">
    <textarea id="note" placeholder="bla bla"></textarea>
</div>

CSS:

/* not working 1 */
 #inputContainer :last-of-type p {
    color: red !important;
}
/* not working 2
 #inputContainer > p:last-child {
    color: red !important;
}
not working 3
 #inputContainer p:last-child {
    color: red !important;
} */
Alex
  • 1,982
  • 4
  • 37
  • 70
  • 2
    You need `#inputContainer p:last-of-type`. `last-child` doesn't work the way you are expecting it to. Have a look at [this thread](http://stackoverflow.com/questions/18995362/last-child-not-working-as-expected/18995451#18995451) for details on how it works. – Harry Aug 13 '15 at 09:33
  • ohh sorry Harry, i did not read your comment and was working on fiddle..you already gave answer before me..ty – Leo the lion Aug 13 '15 at 09:40
  • https://jsfiddle.net/h51rcmag/3/ updated working fiddle – TM Dinesh Aug 13 '15 at 09:55

2 Answers2

5

use css selectors in this way..it will work. use p before last of type..or else it won't work.

#inputContainer p:last-of-type {color:red;}
Leo the lion
  • 3,164
  • 2
  • 22
  • 40
2

:last-of-type is the last element of this specific type...
So p:last-of-type would be the last p element amond all the siblings.

:last-child only triggers if it really is the last child

<div>
  <p></p>
  <p></p>
</div>

Here the second <p> would trigger p:last-child, because it is the last child of the <div> element

<div>
  <p></p>
  <p></p>
  <img />
</div>

Here p:last-child would not trigger, because neither of the 2 <p> are the last child of it's parent, in fact the last child is an <img>
p:last-of-type would be triggered by the 2nd <p> though, because that is the last <p> among all 3 siblings

Inuyaki
  • 1,009
  • 7
  • 9