Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly store a complex jquery selector chain for re-use?

tl;dr? jsFiddle Demo

I have a scenario where I need to re-issue a jquery selector because the dom changes. The selector is non trivial.

$("#protocol :first-child").nextUntil('.sampleDetails','.detailHolder')

To accomplish this I attempted to break it into its parts and store them for re-use:

var selector = [];
selector.push("#protocol :first-child");
selector.push("nextUntil"); 
selector.push(['.sampleDetails','.detailHolder']);

And this way when I needed to build the selector I could use

$(selector[0])[selector[1]](selector[2]);

However, the argument for nextUntil requires two parameters. Using the array does not work, and using "'.sampleDetails','.detailHolder'" did not work as well. I tried to use call and apply but got an error saying that "Uncaught TypeError: Object [object Array] has no method 'pushStack' ".

What is the proper way to store this type of selector chain?

like image 610
Travis J Avatar asked Dec 11 '22 14:12

Travis J


2 Answers

Surely the easy way to do this is with a function, not a complex array of selectors?

var getElements = function() {
    return $("#protocol :first-child").nextUntil('.sampleDetails','.detailHolder');
};

And you can then call it as many times as you like:

var elements = getElements();

Or even:

getElements().show();
like image 159
lonesomeday Avatar answered Jan 05 '23 00:01

lonesomeday


Whilst lonesomeday's answer is the way to go, you can use your original approach with;

jQuery.fn[selector[1]].apply($(selector[0]), selector[2]);

This uses the apply() method, and translates to;

jQuery.fn.nextUntil.apply($('#protocol :first-child'), ['.sampleDetails','.detailHolder']);
like image 27
Matt Avatar answered Jan 05 '23 01:01

Matt