Search code examples
javascriptjqueryselecttreetabledescendant

How do I affect/select all descendants with Treetable plugin using jQuery / javascript


A piece of my HTML code looks like this:

<tr data-tt-id="1">
    <td>Parent</td>
</tr>
<tr data-tt-id="2" data-tt-parent-id="1">
    <td>Child 1</td>
</tr>
<tr data-tt-id="4" data-tt-parent-id="2">
    <td>Child 1's child</td>
</tr>
<tr data-tt-id="3" data-tt-parent-id="1">
    <td>Child 2</td>
</tr>
<tr data-tt-id="5" data-tt-parent-id="3">
    <td>Child 2's child</td>
</tr>

I'm selecting the parent which has data-tt-id="1" by using this:

$('tr[data-tt-parent-id="1"]');

But I want all of the children and children's children too, no matter how deep the tree might be.

As you can see data-tt-id is the child's unique ID and data-tt-parent-id is the ID which the child is appended to.

I was thinking about looping through each one of them, but I have no idea how I would achieve that. How do I select all descendants for the tr that has data-tt-id set to "1"?


Solution

  • function getDescendants(el, curset) {
        curset = curset || $(""); // default to empty set
        var id = el.data('tt-id');
        var children = $("tr[data-tt-parent-id="+id+"]");
        if (children.length) {
            curset = curset.add(children);
            children.each(function() {
                curset = curset.add(getDescendants($(this), curset));
            });
        }
        return curset;
    }
    

    There's probably more idiomatic ways to write this without having to reassign curset = ... in several places, but this works.

    DEMO