Read more

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

Henning Koch
May 19, 2014Software engineer at makandra GmbH

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:

findLastLeaf = ($container) ->
  $children = $container.children()
  if $children.length == 0
    $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) != '')
    if $lastContent.get(0) == $lastChild.get(0)
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more

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

Posted by Henning Koch to makandra dev (2014-05-19 16:23)