如何使用jQuery选择除select元素之外的所有子元素

Sha*_*off 50 jquery drop-down-menu

我有一个div(假设id是"容器"),里面有很多元素,包括一个select元素.除了select之外,我想选择div中的所有内容.我试过的事情:

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

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

也尝试没有通配符后代选择器,所以就像以上所有,但

$("#container:not(#selectorid)")
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 74

您可以简单地省略通配符,因为在这种情况下它是可选的,但请保留空格:

$('#container :not(select)');
Run Code Online (Sandbox Code Playgroud)

或者,使用.not()方法在选择所有子项后过滤掉select:

$('#container').children().not('select');
Run Code Online (Sandbox Code Playgroud)

如果您的问题select仍然是包含的子项,您可以使用.not()方法显式过滤掉它们:

$('#container').children().not('select, option, optgroup');
Run Code Online (Sandbox Code Playgroud)

或仅选择直接儿童:

$('#container > :not(select)');
Run Code Online (Sandbox Code Playgroud)

您可以在交互式jQuery选择器测试器上试用jQuery选择器以获得快速反馈; 尝试举例div :not(ol)div > :not(ol)了解直接child(>)选择器的不同之处.