I hate to admit it, but I'm stuck trying to figure out how to do it.
eg. Pretending you have the following structure:
<div> ... <div> <ul> <li> <a href="..."><img class="foo"/></a> </li> <li> <a href="..."><img class="bar"/></a> </li> <li> <a href="..."><img class="foo"/></a> </li> <li> <a href="..."><img class="baz"/></a> </li> <li> <a href="..."><img class="foo"/></a> </li> </ul> </div> ... <div> <ul> <li> <a href="..."><img class="foo"/></a> </li> <li> <a href="..."><img class="baz"/></a> </li> <li> <a href="..."><img class="foo"/></a> </li> <li> <a href="..."><img class="bar"/></a> </li> </ul> </div> </div>
I am in the jQuery event handler associated with the highlighted "foo" node above. I want to find the next img element, which is "foo" .
There are 2 problems.
- I only want to select the "foo" elements that are in the DOM than the current node on which I am (for example, the "previous" foo, but the current foo are not needed)
- Although I showed nesting as the next exact pattern, the generated code is / can be nested at any level ... so I can't just do .parent (). parent (). parent (). siblings (). find () ... etc.
If you can imagine that every time the browser adds a node to the DOM, it increments the counter and assigns the node this index ... which you could get ... what I want:
var here = $(this).getIndexInDOM();//eg returns 347 $('img.foo').each(function(){ if($(this).getIndexInDOM() > here){//is this past our current index? doSomething($(this));//use it break; } });
The .getIndexInDOM() method obviously does not exist in jQuery ... but I'm curious if anyone has a solution to get the next element that I follow.
The only solution that I can think of at the moment is really elegant and will be pretty lousy if in the second half of the images in the DOM ...
//using vanilla JavaScript var thisImg = theCurrentImageIHave;//some reference to the DOM element var found = false; for(var i=0;i<document.images.length;i++){ if(found){ if(document.images[i].className == 'foo'){ doSomething(document.images[i]); break; } } else { if(document.images[i] == thisImg){ found = true; } } }
source share