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?
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();
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With