jQuery删除了太多的HTML

时间:2011-12-02 19:36:54

标签: jquery html jquery-selectors

我生成的table生成的<td>元素太多了。我打电话给

$('#Container td[class!="SlideInfo"]').remove();

删除其上没有类名<td>的所有不需要的SlideInfo元素。问题是我有一个内部表(子)也被删除。我怎么能告诉jQuery只删除<td>的兄弟姐妹而不是内部兄弟姐妹。

开始

<table>
<tr>
<td class="SlideInfo">
    <table>
        <td class="SlideInfo">
            This gets removed, I know the html is wrong on this but this is an example.
        </td>
    </table>
</td>

<td class="SlideInfo">
    <table>
        <td class="SlideInfo">
            This gets removed, I know the html is wrong on this but this is an example.
        </td>
    </table>
</td>
</tr>
</table>

我致电$('#Container td[class!="SlideInfo"]').remove();并删除了那些不受欢迎的td,但它也删除了我想要的孩子td

3 个答案:

答案 0 :(得分:2)

使用子选择器'&gt;'它只会查找容器的直接子元素之间的匹配元素。试试这个

$('#Container > td[class!="SlideInfo"]').remove();

答案 1 :(得分:1)

我相信正确的选择器就是这个

$('#Container>td[class!="SlideInfo"]').remove();

它只选择#Container的子元素。但是,如果#Container实际上是table元素而不是tr,您可能需要这样的内容:

$('#Container>tr>td[class!="SlideInfo"]').remove();

或者

$('#Container>tbody>tr>td[class!="SlideInfo"]').remove();

答案 2 :(得分:0)

尝试使用“子选择器”。

$('#Container > tr > td[class!="SlideInfo"]').remove();

注意选择器中的大于号。另请注意,您应该在大于号之前使用“tr”标记。

否则,选择器声称应该有一个“td”标记作为标记为“#Container”的任何内容的直接子标记。如果“#container”是“table”标签上的id,我不确定选择器是否正常工作。

“&gt;”说“只选择父母的孩子”。因此,不应选择孙子。这假设您的表的id为“Container”。