Search code examples
jquerydom-traversal

Jquery finding the prev element with same class across dom


One more question on superior jQuery

I want to find a dom element with class say,abc, when i click on an element with same class. Now the search should be exactly the previous element.

Code i have written:

$(this)
    .closest('.abc')
    .parent()
    .prevAll()
    .find('.abc')
    .first()
    .triggerHandler("focus");

This is searching back the parent's previous dom and searching abc, but if the class 'abc' doesnt exist in previous dom, i want to search until it finds abc, Also tried with prevuntil of jquery still no luck.

If anyone can help me out, many thanks.


Solution

  • You can use this to get the previous element:

    var $current = $(this); //the element you have
    var $elems = $('.abc'); //the collection of elements
    
    var $previous = $elems.eq($elems.index($current) - 1); //the one you needed
    

    I would not say this is the most efficient code possible, but without knowing the DOM tree, that's the best I can come up with. If you only rerun $('.abc') when the DOM might have changed and only use the cached version ($elems) it should be fine.