質問

Is there a way to easily do nextUntil, so that the element matched by the selector is included? I have this, which is only fine if there is a previous sibling:

$("#content").find("h3:first").prev().nextUntil("ul:last").wrapAll("<div id='collapse'></div>");
役に立ちましたか?

解決

Remove .prev(), replace .nextUntil with .nextAll and use .addBack() at the end of your selector as shown below:

$("#content").find("h3:first").nextAll("ul:last").addBack().wrapAll("<div id='collapse'></div>");

Pre 1.8 should use andSelf instead of addBack

他のヒント

The workaround I found was to get the length using nextUntil (or prevUntil), then use slice() with this length + 1 on nextAll():

var inclusiveNextUntil = $(this).nextUntil( '.some-class' ).length;
var inclusiveNextUntil = $(this).nextAll().slice( 0 , inclusiveNextUntil + 1 );

It’s clumsy but it works. HTH

Fwiw in the nextAll docs Biziclop mentions adding + *:

$obj.nextUntil('.last-item-to-include + *')  

but this doesn’t work for me :/

Here's what I do. I think it's a bit cleaner than other suggestions.

var elearr = $('selector1').nextUntil('selector2');
var lastele = elearr[elearr.length-1];
elearr.push($(lastele).next());
var s = $("li.start").nextUntil("li.stop");
s = s.add(s.last().next()).add(s.first().prev());
//and do whatever you need to with s

The most intuitive, I think. All made with jQuery methods. No need to search twice. Easy to understand and easy to remember.

I think correct answer is

$("#content").find("h3:first").nextUntil("ul:last").addSelf().wrapAll("<div id='collapse'></div>");

As answered by others, using .addSelf() is the solution for making the starting element inclusive.

$("#content").find("h3:first").nextUntil("ul:last").addSelf().wrapAll("<div id='collapse'></div>");

And to make the ending element inclusive, using the .nextUntil(".class + *") method solved the issue.

$("#content").find("h3:first").nextUntil("ul:last + *").addSelf().wrapAll("<div id='collapse'></div>");

of course you can, just use jQuery nextAll.

'nextAll' will include the following elements matching that selector.

while 'nextUntil' exclude the matching selector element.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top