获取所有不是表的子元素

时间:2011-09-30 10:45:13

标签: javascript jquery

我试图让所有孩子,但跳过表:

我拥有的是:

var allElements = $("body").children();
$.each(allElements, function(i, element)
{
  // Do something
}); // each element

现在我寻找一种方法,即allElements不包含表或函数,如果元素是表,则返回true:

if(element.is("table"));

我什么都没发现。有谁知道这个问题的解决方案?

4 个答案:

答案 0 :(得分:3)

children()接受选择器,因此请使用:not一个:

$('body').children(':not(table)').each(function () {
    // Whatever
});

为了将来参考,您使用is()走在正确的轨道上,但如果jQuery对象中的任何元素与选择器匹配,则返回true,您必须使用如下:

$('body').children().each(function () {
    if (!$(this).is('table')) {
        // It isn't a table, do whatever
    }
});

要继续提供替代方案,您还可以使用not()方法:

$('body').children().not('table').each(function () {
    // Do whatever
});

答案 1 :(得分:2)

使用.not()功能,如下所示:

$("body").children().not('table');

或者,如果要在每个循环中检查更大表达式的一部分,可以使用is(),例如。

if (! $(this).is('table')) { ... }

答案 2 :(得分:2)

可以在一个选择器中完成:

$('body > :not(table)').each...

答案 3 :(得分:1)

$('body').children().each(function(){
    if(!$(this).is('table'))
    alert($(this).html())
})

此处的示例http://jsfiddle.net/S2tUS/

或者这个

$('body').children(':not(table)').each(function(){
    alert($(this).html())
})

http://jsfiddle.net/S2tUS/2/

相关问题