获取元素的父级td,该级别直接位于具有特定类

时间:2015-12-17 21:53:57

标签: jquery html jquery-selectors nested-table

我在网页中有一个复杂的表结构,如下所示。可能会有更深层次的表格嵌套。

我正在尝试找到一个jQuery选择器来查找与给定输入元素最接近的td,并添加了约束条件,即此td的tr应该具有&class 39' class1'。

问题:如何在jQuery的帮助下掌握上面段落中描述的单个“td”?我尝试了一些代码,但没有成功。

例如,如果给定的输入元素是firstname,则紧跟此元素的td将不是我要查找的元素,但带有<!--this is the td I am trying to get-->的注释的td是正确的td。

我试过跟随选择器来获取这个td但是它返回的6个td DOM元素,当时我只期待一个。您可以在此网址上查看此代码:demo for this scenario

我尝试过的代码,但它不起作用

$('#firstName').parents("tr.class1").find("td");

嵌套表的Html

<table>
   <tr class='class1'>
      <td>
         <!--some content here-->
      </td>
      <td><!--this is the td I am trying to get-->
         <table>
            <tr>
               <td>
                  First Name 
               </td>
               <td>
                  <input type='text' id='firstname'>  
               </td>
            </tr>
            <tr>
               <td>
                  Last Name 
               </td>
               <td>
                  <input type='text' id='lastname'>
               </td>
            </tr>
         </table>
      </td>
   </tr>
</table>

1 个答案:

答案 0 :(得分:1)

要实现您的要求,您需要将closest()与直接子选择器>一起使用,以获得父td。试试这个:

var $td = $('#firstname').closest('.class1 > td');

Example fiddle

相关问题