Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)") 
like image 817
Shawn J. Goff Avatar asked Jul 14 '09 14:07

Shawn J. Goff


People also ask

How do you get the children of the $( this selector?

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.

How do you get children of children in jQuery?

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.

Which will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

Can we get the children element from the parent element using jQuery?

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.


2 Answers

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.

like image 148
Martijn Pieters Avatar answered Sep 29 '22 01:09

Martijn Pieters


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'; } 
like image 28
Jeff Avatar answered Sep 29 '22 01:09

Jeff