WindowsMaker
WindowsMaker

Reputation: 3400

jquery find top level tables in children

I am trying to find the all table elements that are not descendant of table elements. For example i want to select all these in between **

<div>
    <**table**>
        <tr>...</tr>
        <tr>...</tr>
        <tr>
            <table>
                ....
            </table>
        </tr>
    </**table**>
    <div>
        <**table**>
            ...
        </**table**>
    </div>
</div>

Essentially i want to find all top level tables and not their descendant tables. The structure of the DOM is not guaranteed so i can't just use $("div > table")

Upvotes: 1

Views: 289

Answers (3)

Nishanth Matha
Nishanth Matha

Reputation: 6081

ok consider this:

$("table").addClass("test"); // add new class to all the tables <br/><br/>
$("tr").children().removeClass("test"); // remove this class for all the children of tr<br/><br/>
$("td").children().removeClass("test"); // remove this class for all the children of td<br/><br/>
$(".test") //now select the upper most table with its class

Upvotes: 1

Jon
Jon

Reputation: 437376

A straightforward solution is to select all tables and filter out those that have a table ancestor:

var $tables = $("table")
                .filter(function() { return $(this).parents("table").length == 0; });

Upvotes: 2

Master Slave
Master Slave

Reputation: 28519

You can select all the tables that don't have a child table element

$("table:not(:has(table))")

Upvotes: 3

Related Questions