简体   繁体   中英

How to get all elements after selected element

How do I include the last element aswell?

 $('div.current').nextUntil("div:last").css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

You could just use nextAll() instead:

 $('div.current').nextAll().addClass('foo'); 
 .foo { color: #00F; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

You could use andSelf method in combination with next() method.

andSelf method adds the previous set of elements on the stack to the current set.

 $('div.current').nextUntil("div:last").andSelf().next().css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

You could use the general sibling combinator ~ in your selector

 $('div.current ~ div').css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

You could just pass no parameter inside nextUntil() and it will select all the next following elements.

Or maybe use nextAll() .

 $('div.current').nextUntil().css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

Use nextAll method of jquery instead of nextUntil.

 $('div.current').nextAll().css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

Here's what you wanted to do with your code ^^

 $('div.current').nextUntil("html").css("color", "blue"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>First</div> <div>Second</div> <div class="current">Third</div> <div>Fourth</div> <div>Fifth</div> <div>Sixth</div> <div>Seventh</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM