假设没有涉及库.
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';
}
Run Code Online (Sandbox Code Playgroud)
如果你有 jQuery,这很容易。如果你的 HTML 是这样的:
<table>
<tr><td><div class="mydiv">hi</div></td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)
然后你可以这样说:
$('div.mydiv').closest('table').addClass('someclass');
Run Code Online (Sandbox Code Playgroud)
该closest函数在 DOM 树中向上查找,直到到达与您给出的选择器匹配的元素(在本例中为table)。
| 归档时间: |
|
| 查看次数: |
11286 次 |
| 最近记录: |