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 |5 Answers
Reset to default 11Assuming 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!
<tbody>
between<tr>
and<table>
in the parentNode chain. Broswers insert it implicitly. – ori Commented Jan 30, 2012 at 16:07