Posted over 7 years ago. Visible to the public.

Get the last leaf of a DOM tree (while considering text nodes)

I use this to simulate the (non-existing) :last-letter CSS pseudoclass, e. g. to insert a tombstone Archive at the end of an article:

Copy
findLastLeaf = ($container) -> $children = $container.children() if $children.length == 0 $container else $lastChild = $children.last() $lastContent = $container.contents().filter(-> # Only return nodes that are either elements or non-empty text nodes @nodeType == 1 || (@nodeType == 3 && _.strip(@nodeValue) != '') ).last() if $lastContent.get(0) == $lastChild.get(0) findLastLeaf($lastChild) else $container

Please note that you can't simply say $container.descendants.last() or something similar, since jQuery is ignorant of text nodes.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Henning Koch
Last edit:
over 7 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more