javascript 获取元素的表父级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9066792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Table Parent of an Element
提问by hassan sleh
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?
我在表中动态创建了一个类 x 的 div。我怎样才能用 JavaScript 捕捉这个 div 的表父级并给它一个特定的类?
Passing through the tr and td parent Node didn't worked. Any ideas?
通过 tr 和 td 父节点不起作用。有任何想法吗?
回答by Quentin
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';
}
回答by cambraca
If you have jQuery, this is very easy. If your HTML is something like this:
如果你有 jQuery,这很容易。如果你的 HTML 是这样的:
<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
).
该closest
函数在 DOM 树中上升,直到它到达与您提供的选择器匹配的元素(在本例中为table
)。
回答by Goodbye StackExchange
This is a relatively old answer, but now we have .closest
which can traverse through elements until it finds the table:
这是一个相对较旧的答案,但现在我们.closest
可以遍历元素直到找到表:
var td = document.getElementById('myTdElement');
var table = td.closest('table');
if (table) {
table.className += ' certain';
}
Compatibility:
兼容性:
回答by Marc B
Assuming the new div's already inserted into the DOM tree, you can use jquery:
假设新的 div 已经插入到 DOM 树中,您可以使用 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...
裸 JavaScript 可以做类似的事情,但你必须编写一个循环来迭代每个 .parentNode,测试它是否是一个表,等等......
回答by Manish Shrivastava
Using jQuery If your HTML is something like this:
使用 jQuery 如果你的 HTML 是这样的:
<table>
<tr><td><div class="divClass">Content</div></td></tr>
</table>
Then you can call parent table like:
然后你可以像这样调用父表:
$('div.divClass').parent();
$('div.divClass').parent();
below code will give html of your table:
下面的代码将给出你的表格的 html:
alert($('div.divClass').parent().html());
警报($('div.divClass').parent().html());
You can use $('div.divClass').parent();
as you want ...
您可以随意使用$('div.divClass').parent();
...
Cheers!
干杯!