Question

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.

Was it helpful?

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.

OTHER TIPS

Here is a quick and dirty way:

$('.abc').click(function(){
    var clicked = this;
    var last;
    // Go though all elements with class 'abc'
    $('.abc').each(function(){
        if(this == clicked) return false;
        last = this;
    });
    if(last) $(last).triggerHandler("focus");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top