Reputation: 4984
Hi i have to find the "findme" div in dom structure after a particular div and find the first instance after the div using one Jquery. following may be the dom structure:
ex1:
<div class="abc"></div>
<div class="findme"></div>
ex2:
<div class="abc"></div>
<div>
<div class="findme"></div>
</div>
ex3:
<div>
<div class="abc"></div>
</div>
<div>
<div class="findme"></div>
</div>
ex4:
<div>
<div class="abc"></div>
</div>
<div class="findme"></div>
above are some examples of dom structure in which i want to find "findme" first div
after "abc" div using jquery
i tried using after(),closest().nextAll().first()
but i am not getting the query to match above all examples .
so please can anyone help me to find the div first element ("finme") after "abc" div
I want find the next "findme" div in complete dom after "abc" div and first occurrence of after "abc" div above are some examples the dom can be
Upvotes: 0
Views: 341
Reputation: 93561
The only way I could find to get this to work for all cases is to walk the entire DOM sequentially with a filter:
var foundAbc;
$('*').filter(function() {
if ($(this).hasClass('abc')) {
foundAbc = true;
} else {
if (foundAbc && $(this).hasClass('findme')) {
foundAbc = false;
return true;
}
}
return false;
}).css('color','red');
JSFiddle: https://jsfiddle.net/TrueBlueAussie/LnLf79od/2/
You could wrap this behavior in a jQuery extension method if you wanted to make it reusable.
$.findNext = function(selector1, selector2) {
var foundAbc;
return $('*').filter(function() {
if ($(this).is(selector1)) {
foundAbc = true;
} else {
if (foundAbc && $(this).is(selector2)) {
foundAbc = false;
return true;
}
}
return false;
});
}
and use like this:
$.findNext('.abc', '.findme').css('color', 'red');
JSFiddle: https://jsfiddle.net/TrueBlueAussie/LnLf79od/3/
Upvotes: 1