How to properly store a complex jquery selector chain for reuse?

TL, dr? jsFiddle Demo

I have a scenario where I need to re-release the jquery selector because dom is changing. The selector is not trivial.

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

To do this, I tried to break it into pieces and save them for reuse:

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

And so, when I needed to create a selector, I could use

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

However, the nextUntil argument requires two parameters. Using an array does not work, and using ".sampleDetails", ". DetailHolder" does not work. I tried using call and apply , but got the error message "Uncaught TypeError: Object [object Array] has no method 'pushStack' " .

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

+4
source share
2 answers

Surely a simple way to do this is a function, not a complex array of selectors?

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

And you can call it as many times as you want:

 var elements = getElements(); 

Or even:

 getElements().show(); 
+10
source

While lonesomeday's answer is the way to go, you can use your original approach:

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

The apply() method is used here and translated into:

 jQuery.fn.nextUntil.apply($('#protocol :first-child'), ['.sampleDetails','.detailHolder']); 
+3
source

Source: https://habr.com/ru/post/1487955/


All Articles