How to select all content between two tags in jQuery
Two methods in particular would be very useful solving this problem: .nextUntil
, and .andSelf
. The first will grab all of the siblings following your selector, and the latter will lump in whatever is matched by your selector as well, giving you one jQuery object that includes them all:
$("#heading2")
.nextUntil("#heading3").andSelf()
.css("background", "red");
This results in the following:
Here is the solution I use for my projects:
jQuery selector
(function ($) {
$.fn.between = function (elm0, elm1) {
var index0 = $(this).index(elm0);
var index1 = $(this).index(elm1);
if (index0 <= index1)
return this.slice(index0, index1 + 1);
else
return this.slice(index1, index0 + 1);
}
})(jQuery);
Usage
$('body').between($('#someid'), $('#someid2')).each(function () {
// Do what you want.
});