Friday, May 18, 2012

How do I use jQuery to select all children except a select element


I have a div (let's say the id is "container") with many elements in it, including a select element. I'd like to select all everything in the div except the select. Things I've tried:




$("#container *:not(select)")
$("#container *:not(#selectorid)")

//put a div around the select and...
$("#container *:not(#selectorcontainer)")
$("#container *:not(#selectorcontainer *)")
$("#container *:not(#selectorcontainer, #selectorcontainer *)")



Also tried without wildcard descendant selector, so just like all the above, but




$("#container:not(#selectorid)")


Source: Tips4all

7 comments:

  1. You can simply omit the wildcard as it is optional in this case, but keep the space:

    $('#container :not(select)');


    Alternatively, use the .not() method to filter out the select after selecting all children:

    $('#container').children().not('select');


    If your problem is that children of select are still included, you could explicitly filter those out with the .not() method:

    $('#container').children().not('select, option, optgroup');


    or select direct children only:

    $('#container > :not(select)');


    You can try out jQuery selectors at the interactive jQuery selector tester for quick feedback; try for example div :not(ol) or div > :not(ol) to get a feel for what difference the direct child (>) selector makes.

    ReplyDelete
  2. You can also try it using traversing methods:

    $('#container').children().not('#selectorId');


    or being a final option:

    $('#container').children().filter(function(){
    return $(this).attr('id') !== 'selectorId';
    }

    ReplyDelete
  3. The :not(selector) should work. But if you can't figure it out, you can select all the children, and then remove any SELECT elements afterwards. That, or manually skip those particular elements whenever you're running through your collection later.

    ReplyDelete
  4. It is not clear what you actually want from your question.
    :not(select) will filter out the select from all the descendants but it will not out the select descendants. If this is your issue then try the following

    Demo

    $("#container *").filter( function(){
    return $(this).closest('select').length === 0
    })

    ReplyDelete
  5. http://stackoverflow.com/questions/1109835/quick-html-jquery-question
    Two approaches to the problem: The one with 8 votes is probably the one you are looking for.

    ReplyDelete
  6. maybe this can help you
    where 3 is the #select

    try one of these:
    $("#container *:not(eq(3))
    $("#container").children().filter(:not(eq(3)));

    ReplyDelete
  7. $(#container select).siblings()


    http://docs.jquery.com/Traversing/siblings

    ReplyDelete