查找特定父ID的子ID - javascript

时间:2016-06-02 18:10:55

标签: javascript jquery dom

我有以下两个TR HTML DOM树。我必须找到id necessary的总计数仅映射到id successDesktop

<TR class="greybgContent" id="7">
    <TD align="center">
        <DIV class="necessary" id="necessary">&nbsp;</DIV>
        &nbsp;
    </TD> 
    <TD>8 Bureau Consent </TD>
    <TD id="successDesktop">
        <DIV class="floatLeft selectWidth15">
            <DIV class="available"></DIV>
        </DIV>
        <DIV class="floatLeft selectWidth85 greenText">Uploaded</DIV>
    </TD>
</TR>
<TR class="greybgContent" id="8">
    <TD align="center">
        <DIV class="necessary" id="notrequired">&nbsp;</DIV>
        &nbsp;
    </TD> 
    <TD> 9 Address Details</TD>
    <TD id="successDesktop">
        <DIV class="floatLeft selectWidth15">
            <DIV class="available"></DIV>
        </DIV>
        <DIV class="floatLeft selectWidth85 greenText">Uploaded</DIV>
    </TD>
</TR>

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,我相信这可能是你想要完成的(我使用jQuery)。

$(document).ready(function(){

    // set the initial count to zero
    var count = 0;

    // loop over all table rows
    $('tr').each(function(index, obj){

    // try to find an element with the id 'successDesktop'
    if ($(obj).find('#successDesktop').length > 0) 
    {
      // if 'successDesktop' exists, look for an element with id 'necessary'
      if ($(obj).find('#necessary').length > 0)
      {
         // increase the count
         count++;
      }
    }
  });
  console.log('count: ', count);

});

此外,您可能希望使用类而不是ID来表示必要的&#39;和&#39; successDesktop&#39;,因为ID仅用于每页一次。类可以重复使用。

相关问题