Today I was scratching my head wondering why a basic last-child selector wasn't working on a page I was styling up.

A quick look at the DOM reminded me that Ember likes to litter the DOM with <script> tags.

So instead of having a nice list like;

<ul>
  <li>One</li>
  <li>Two</li>
</ul>

We get something similar to

<ul>
  <li>One</li>
  <script id="metamorph-1-start" type="text/x-placeholder"></script>
  <script id="metamorph-1-end" type="text/x-placeholder"></script>
  <li>Two</li>
  <script id="metamorph-2-start" type="text/x-placeholder"></script>
  <script id="metamorph-2-end" type="text/x-placeholder"></script>
</ul>

When we use last-child in CSS it is normally on a repeating collection of things so we don't really think about the elements around them. In the example above however <li>Two</li> is not the last-child of anything, that last <script> tag is.

In comes last-of-type

Luckily there is a way around this with the last-of-type selector in CSS. This works exactly the same as last-child only it takes the type of the elements into consideration.

This means the following CSS will now work as expected;

ul li::after { content: ", "}
ul li:last-of-type::after { content: ""}

Not just Ember

Whilst this is the first time I have had to think about things like this, I think I will be using this method from now on – it is more strict and acts exactly how I want it to act. With front end web development at the moment there could be several things making changes to the DOM on the fly and potentially knocking out things like last-child

Why not read some more of our JavaScript posts?