Search code examples
javascriptjqueryparents

How to find an ancestor element and query its metadata


I have an html which contains nested tables:

<table ....
<tbody ...
<tr ...
    <td class="Field">item1_1</td>
        <td class="Value">
        <table ...
        <tbody...
        <tr
            <td class="Field">0</td>
            <td class="Value">
            <table ...
                ....

The clickable element are the Fields. When the user clicks a field, I need to find the table which contains its table (2 tables up) and check its metadata. I tried to use:

field.parents("table")[1]

This returns the right table but it doesn't allow me to query its metadata:

field.parents("table")[1].data("isArray")

Can you please help me figure out how to query the metadata of the containing table?

Thanks, Li

p.s. I've only managed to do it by using:

field.parent().parent().parent().parent().parent().parent().parent().parent().data("isArray")

but I really want to avoid such ugliness.


Solution

  • The problem you're having is that array indexing the jquery object will return a dom object. You can instead use eq to get you a jquery object.

    field.parents("table").eq(1).data("isArray")
    

    If you are able to modify the html. An even cleaner approach would be to assign a class to the table you are trying to get and then use closest.

    field.closest(".someClass").data("isArray")