Why doesn't the ":last-child" selector apply when <body> is the parent?

dom, html, jquery, jquery-selectors

Solution

If you look at the DOM, JS Bin inserts some `script` elements before the closing `</body>` tag, which prevents any of the `div`s from matching `div:last-child`. Remember that although `script` elements are (usually) not rendered, they do exist in the DOM just like any other HTML element, and as a result will affect selector matching.

The last `div` is in fact the last of its type, even if it isn't the very last child of `body`; you can verify this by switching to `:last-of-type` and it will match.

As mentioned in the comments, Stack Snippets does this as well:

div:last-child { text-decoration: underline; }
div:last-of-type { color: red; }
<body>
  <div>Red but no underline</div>
</body>

Problem

I have this simple HTML: ``` <body> <a> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </a> </body> ``` The divs are children of `<a>`. From jQuery: `:last-child Selector` — Selects all elements that are the last child of their parent. However, when running this code in JSBin: ``` $("div:last-child" ).css('background-color','red') ``` It yields this rendered output: Even if we remove `<a>` so that `divs` will be direct children of `<body>`: ``` <body> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </body> ``` The result is that nothing is painted: (http://jsbin.com/kamepu/4) Those `divs` are children of `<body>`, so why isn't it working?

Original source

Related problems