Return text without children

by Alvin Olavarrieta

HTML

<ul>
  <li>AAA</li>
  <li>BBB
    <ul>
      <li>111
        <ul>
          <li>XXX</li>
        </ul>
      </li>
      <li>222</li>
    </ul>
  </li>
  <li>CCC</li>
</ul>

<hr>

<table><tr id="tr"></tr></table>

CSS

td {
    vertical-align: top;
}

JavaScript

//Columns

var $tr = $("#tr");
function text(x) { // returns text without children
    return x.clone()
            .children()
            .remove()
            .end()
            .text();
}

function add(elem, level) {
    elem.children().each(function() {
        var $this = $(this);
        var appendToThis = $tr.find("td").eq(level);
        var appendedText = text($this) + "<br>";
        if(appendToThis.length) {
            appendToThis.append(appendedText);
        } else {
            $tr.append($("<td>").append(appendedText));
        }
        var children = $this.children();
        if(children.length) {
            add(children, level + 1);
        }
    });
}

add($("ul:eq(0)"), 0);