Edit: My solution, based on the chosen answer:
var $brs,
$chunks = [];
$brs = $('hr:eq(1)').nextUntil($('hr:eq(2)')).filter('br');
$chunks.push($('hr:eq(1)').nextUntil($brs.eq(0)));
for (i = 0; i < $brs.length - 1; i++) {
$chunks.push($brs.eq(i).nextUntil($brs.eq(i+1)));
}
I have an unusual case that’s resulted from a VERY poorly written website I am attempting to parse with javascript. I won’t delve into the fun parsing, but I’ve finally managed to mangle it down to a meaningful structure. I now have a DOM that looks like this (for all intents and purposes, look at this as a flat listing of tags, each closed before the next starts):
<hr>
<a>
<span class="desc">
[<a>*] // 0 or more anchor tags can show up here
<br>
<br>
<a>
<span class="desc">
[<a>*]
<br>
<br>
.
.
.
What I am looking to do is grab each cluster of tags into its own array/jquery object/whatever by, essentially, running a .split() on the <br> tags. It is possible to do such a thing? if not, how would you go about separating this into chunks? So the result would be this:
[<a>, <span class="desc">, <a>],
[<a>, <span class="desc">],
[<a>, <span class="desc">, <a>, <a>, <a>],
[<a>, <span class="desc">],
...
I’m not sure why you’re doing that instead of just modifying the html, but it’s technically possible using the
.nextUntiljQuery method.Starting at the
hr, select all sibling elements until the firstbrand push the jQuery set into an array. Repeat this process between each pair of line-breaks..eq()can be used to target a specificbr.Of course the specified selectors will find all
brorhrelements on the page, so you will need to make your selectors more specific if there are others. You can do this by providing a context for the selector to look in.If you don’t want to keep the entire jQuery object in the array (though you probably do want to because you can retrieve DOM elements using the regular array methods — with the added benefit of having all of the jQuery functionality available) you can convert the jQuery object to a regular array. jQuery’s
.toArray()method will take care of that for you: