JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<p>Hello</p>
<div>
<p>Foo</p>
<p class="bar">Bar</p>
<p>rawr!</p>
</div>
<p>bop</p>
<input/>
<div>
<p>Another</p>
<div>
<span>something</span>
<p>deep!</p>
</div>
</div>
</div>
<p>last</p>
JavaScript
(function($) {
function nextNode(node, omitChildren) {
var sibling, parentNode;
if (!omitChildren && node.hasChildNodes()) {
return node.firstChild;
} else {
sibling = node.nextSibling;
if (sibling) {
return sibling;
} else {
parentNode = node.parentNode;
return parentNode ? nextNode(node.parentNode, true) : null;
}
}
}
$.fn.nextInDocument = function(selector) {
var node = this[0], $node;
while ( (node = nextNode(node)) ) {
$node = $(node);
if ($node.is(selector)) {
return $node;
}
}
return null;
}
})(jQuery);
alert($('.bar').nextInDocument('p').html()); // <p>rawr</p>
alert($('.bar').nextInDocument('p').nextInDocument('p').html()); // <p>bop</p>
alert($('.bar')
.nextInDocument('p')
.nextInDocument('p')
.nextInDocument('p')
.nextInDocument('p')
.nextInDocument('p').html()); // <p>last</p>