How to select all content between two tags in jQuery

ぐ巨炮叔叔 提交于 2019-11-26 16:07:35

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:

Lasse Espeholt

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.
});
jesper
$('#secondSelector').prevAll('#firstSelector ~ *')
Ricardo Vega

Yeah, you're right. This will only avoid the desired selector. Maybe it needs to be more detailed:

$(firstSelector).nextAll().not(secondSelector).not($(secondSelector).nextAll()).text()
Ricardo Vega

Maybe, with

$(selectorForFirstHeading).nextAll().not(selectorForLastHeading).text()

Why do I use text()? Because html() will only return the inner HTML of the first result element.

I feel as if the accepted answer needs a bit of an update since the release of jQuery 1.8 and later. .andSelf() has been deprecated. In its place, we have .addBack(). The documentation explains everything you need to know.

disc0dancer

If your elements are at the same level, something like this:

<h1 id="heading1">...</h1>
<ul>...</ul>
<p>...</p>
<ul>...</ul>
<p>...</p>
<h1 id="heading2" >...</h1>

That is, your next heading element is not a child of an element at the same level as the first heading element. You can try this code:

// This will get all the following siblings of <h1 id="heading1"> except those that are headings themselves
var elements = $('#heading1').nextAll().not("h1");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!