Next Element In *entire* Document After Certain Element
This is a variation on a question asked so many times. Given any element, I want to be able to find any other element after it in the entire document. It can be a sibling but it co
Solution 1:
How about this? It's a generic solution that uses DOM methods to traverse nodes in turn and tests each against the jQuery selector.
jsFiddle: http://jsfiddle.net/PsEdZ/3/
(function($) {
functionnextNode(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(parentNode, true) : null;
}
}
}
$.fn.nextInDocument = function(selector) {
var node = this[0], $node;
while ( (node = nextNode(node)) ) {
$node = $(node);
if ($node.is(selector)) {
return$node;
}
}
returnnull;
}
})(jQuery);
Solution 2:
This should work. Not really sure it's useful, though...
;(function($)
{
$.fn.nextInDocument = function(s)
{
var self = this,
next;
do
{
next = self.nextAll(s).first();
self = self.parent();
}
while (self.length && !next.length);
returnnext;
};
})(jQuery);
Solution 3:
(function(jQuery) {
jQuery.fn.extend({
nextInDocument: function(a) {
if (jQuery(this).next(a).length === 0) {
//console.log($(this).parent().nextInDocument('p'));jQuery(this).parent().nextInDocument(a);
}
elsereturnjQuery(this).next(a);
}
});
})(jQuery);
Solution 4:
Here's a POJS version:
functionnextInDocument(el, tagName) {
var node, nodes = document.getElementsByTagName('*');
var start = false;
tagName = tagName.toLowerCase();
for (var i=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i];
if (!start) {
if (node == el) start = true;
} else {
if (node.tagName.toLowerCase() == tagName) {
return node;
}
}
}
}
Solution 5:
take look at my code:
HTML
<div><p>Hello</p><div><p>Foo</p><p>Fooooo</p><pclass="bar">Bar</p><p>rawr!</p></div><p>bop</p><input/><div><p>Another</p></div></div><p>last</p><aclass="show"href="#">!!!</a>
JS
$(function() {
i = 0;
start = 0;
$('p').each(function() {
if ($(this).hasClass('bar')) {
start = i;
}
i++;
});
$('a.show').click( function(){
alert($('p').eq(start+4).text());
});
});
change start+X
and you will get next 'p' tag
Post a Comment for "Next Element In *entire* Document After Certain Element"