Em1
Em1

Reputation: 1095

get all child elements that are not a table

I try to get all children, but skip tables:

What I have is:

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

Now I look for either a way, that allElements does not include tables or a function, that returns true, if an element is a table:

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

I do not find anything. Does anyone know a solution for this issue?

Upvotes: 1

Views: 639

Answers (4)

Sedat Başar
Sedat Başar

Reputation: 3798

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

an example here http://jsfiddle.net/S2tUS/

or maybe this

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

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

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

Can do it in a single selector:

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

Upvotes: 2

a'r
a'r

Reputation: 36999

Use the .not() function like this:

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

Or, if you want to check as part of a larger expression within the each loop, you can use is(), eg.

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

Upvotes: 2

Matt
Matt

Reputation: 75317

children() accepts a selector, so use the :not one:

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

For future reference, you were on the right track with is(), but as it returns true if any of the elements in the jQuery object matches the selector, you'd have to use it as follows:

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

To keep providing alternatives, you could also use the not() method:

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

Upvotes: 3

Related Questions