hassan sleh
hassan sleh

Reputation: 307

Get Table Parent of an Element

I created dynamically a div with a class x in a table. How can I with JavaScript catch the table parent of this div and give it a certain class?

Passing through the tr and td parent Node didn't worked. Any ideas?

Upvotes: 6

Views: 18769

Answers (5)

Blue
Blue

Reputation: 22911

This is a relatively old answer, but now we have .closest which can traverse through elements until it finds the table:

var td = document.getElementById('myTdElement');
var table = td.closest('table');
if (table) {
    table.className += ' certain';
}

Compatibility:

Upvotes: 2

Manish Shrivastava
Manish Shrivastava

Reputation: 32040

Using jQuery If your HTML is something like this:

<table>
  <tr><td><div class="divClass">Content</div></td></tr>
</table>

Then you can call parent table like:

$('div.divClass').parent();

below code will give html of your table:

alert($('div.divClass').parent().html());

You can use $('div.divClass').parent(); as you want ...

Cheers!

Upvotes: 0

Marc B
Marc B

Reputation: 360662

Assuming the new div's already inserted into the DOM tree, you can use jquery:

$(div_node).parents('table')[0].addClass('certain_class');

Bare javascript can do similar things, but you'll have to write a loop to iterate up each .parentNode, test if it's a table, etc...

Upvotes: 0

Quentin
Quentin

Reputation: 943537

Assuming that no libraries are involved.

function getNearestTableAncestor(htmlElementNode) {
    while (htmlElementNode) {
        htmlElementNode = htmlElementNode.parentNode;
        if (htmlElementNode.tagName.toLowerCase() === 'table') {
            return htmlElementNode;
        }
    }
    return undefined;
}

var table = getNearestTableAncestor(node);
if (table) {
    table.className += ' certain';
}

Upvotes: 11

cambraca
cambraca

Reputation: 27837

If you have jQuery, this is very easy. If your HTML is something like this:

<table>
  <tr><td><div class="mydiv">hi</div></td></tr>
</table>

Then you can say something like:

$('div.mydiv').closest('table').addClass('someclass');

The closest function goes up in the DOM tree until it reaches an element that matches the selector you give (in this case, table).

Upvotes: 3

Related Questions