I have this simple HTML :
1
2
3
4&l
:last-child
returs true is the very last child is of this type (div
in this case).
JSBin links script
s at the bottom of the page (before </body>
), so :last-child
can works with script
element only.
Solution is to move scripts into head
section using document.ready
or after </body>
.
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>