Check if element is before or after another element in jQuery

后端 未结 9 1542
花落未央
花落未央 2020-12-23 16:23

Let us suppose I have this markup

First

Hi

Hello

Second

相关标签:
9条回答
  • 2020-12-23 17:07

    Keeping in mind Rocket's answer I prefer to use .index() approach like following:

    $.fn.isAfter = function(sel){
        return $(this).index() > $(sel).index();
    };
    $.fn.isBefore= function(sel){
        return $(this).index() < $(sel).index();
    };
    

    It seems more clear for reading/understanding and works perfectly in rows selection.

    0 讨论(0)
  • 2020-12-23 17:07

    The accepted answer only works if the elements are at the same level. One approach to solve it if you want to locate which element is first regardless of the level is:

    1. Set a temporary attribute to each element with the same value
    2. Use a jquery selector to locate the first element with that attribute value
    0 讨论(0)
  • 2020-12-23 17:10

    Here is a fiddle

    $('p').each(function() {
        previousH3 = $(this).prevAll('h3');
        nextH3 = $(this).nextAll('h3');
    
        if (previousH3.length > 0 && nextH3.length > 0) {
            $(this).css('color', 'red')
        }
    
    });
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题