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)")
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.
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.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With