jQuery: Find next element that is not a sibling

前端 未结 2 1916
滥情空心
滥情空心 2021-01-31 08:44

Let\'s say I have following HTML:


    X1


    
        

        
相关标签:
2条回答
  • 2021-01-31 08:50

    Select all elements with class x, calculate the index of the current element and get the element with the index + 1:

    var $x = $('.x');
    var $next = $x.eq($x.index(this) + 1);
    

    This works because elements are selected in document order. You only have to select all .x elements once on page load (if they are not dynamically created).

    0 讨论(0)
  • 2021-01-31 09:06

    You could use xpath:

    document.evaluate('following::*[@class="x"], elt, null, XPathResult.ANY_TYPE, null);
    

    or you could use a walker:

    var walker = document.createTreeWalker(elt, NodeFilter.SHOW_ELEMENT, function(node) {
        return node.classList.has('x');
    });
    
    while (walker.nextNode) {
        do_something_with(walker.currentNode);
    }
    
    0 讨论(0)
提交回复
热议问题