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 Show archive.org snapshot at the end of an article:

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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)