最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Table Parent of an Element - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Nov 2, 2015 at 23:16 Nathan 8,9209 gold badges54 silver badges82 bronze badges asked Jan 30, 2012 at 16:02 hassan slehhassan sleh 3071 gold badge4 silver badges12 bronze badges 1
  • 2 since your question has already been answered, I'll just comment that your script was proabably unaware of <tbody> between <tr> and <table> in the parentNode chain. Broswers insert it implicitly. – ori Commented Jan 30, 2012 at 16:07
Add a comment  | 

5 Answers 5

Reset to default 11

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';
}

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).

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:

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...

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!

发布评论

评论列表(0)

  1. 暂无评论