views:

76

answers:

4

Hello,

I need to remove tags going after #first and only in #container. How can I do it with jQuery?

<div id="container">
  <div id="first"></div>
  <div id="remove_me_1"></div>
  <div id="remove_me_2"></div>
  <div id="remove_me_3"></div>
  <a href="" id="remove_me_too">Remove me too</a>
</div>

Thank you

+1  A: 
$.("#container #first ~ *").remove();
Emil Vikström
-1 the universal selector * should be avoided whereever possible.
jAndy
@jAndy, is there any evidence that your statement applies in the context of jQuery? I know CSS selectors are matched right to left, but I'm not so sure jQuery does the same. It may be the case with `querySelectorAll` though.
Ionuț G. Stan
sizzle matches from right to left, yes.
jAndy
So Sizzle matches right to left when not using `querySelectorAll` actually?
Ionuț G. Stan
Ok, it appears `querySelectorAll` does the same right to left processing.
Ionuț G. Stan
You could always do something like: `$("#container #first").find("~ *")` to limit the search first.
DisgruntledGoat
I'm not even sure if that would avoid the universal selector to grab all nodes first. However, the star is just bad ;)
jAndy
+10  A: 

You can use nextAll method: http://api.jquery.com/nextAll/

$("#first").nextAll().remove();
mamoo
+1 nice and simple, deleted my slightly (but only slightly) more complicated answer.
T.J. Crowder
The selector should be `#container #first` as required in the question.
DisgruntledGoat
@DisgruntledGoat, there should be a single `#first` element in the page.
Ionuț G. Stan
@Ionut: yes, but it may not always be in `#container` on every page.
DisgruntledGoat
A: 
$('#container').children(':not(#first)').remove();
jAndy
Wouldn't this remove siblings before #first if there are any?
Emil Vikström
A: 
$("#container :gt(0)").remove();
karim79