TD In Table If/Else

TD In Table If/Else

本文关键字:Else If Table In TD      更新时间:2023-09-26

我在一个表中有一个。我想要一个if/else语句,如果td在表中,则将92添加到变量x。

这是我得到的代码,但显然if/else不是我想要的。

//Html
<table id="Tableleft">
   <tr>
     <td id="92">Text 1</td>
   </tr>
</table>
//Javascript
var x = 0
if ( document.getElementByID('92')) { 
//Help Here Please
}

使用elem.parentNode迭代DOM树以查看祖先是否为<table>

我对的要求定义非常宽容"如果TD在表中",您可能想要更严格(例如,仅允许<tr>, <tbody>, <thead>, <tfoot><table>作为您的+92行动工作的有效祖先)。

var x = 0,
    td = document.getElementByID('92'),
    e; // we'll use this in our loop
if (td) { // `td` is not `null` -> we found a node with _id_ `92`
    e = td;
    while (e = e.parentNode) { // iterate up the DOM tree
        if (e.tagName === 'TABLE') { // the `td` node has an ancestor `<table>`
            x += 92;
            break;
        }
    }
}

使用普通数字作为id属性可能会产生意想不到的结果。为了获得最佳效果,将第一个字符设置为a-zA-Z,并避免在选择器中使用具有特殊含义的字符.#:@