Question - brief
Can you call a jQuery method in a chain, from a variable, or can you only use these methods on jQuery objects / elements?
Explanation
we have a custom function
$.fn.example = function(){
$.each(this, (index, item) => {
console.log(item);
}
return this;
}
This will loop through an object and console.log()
each item within.
Let's say there are 3 <p>
tags within the HTML.
<p>One</p>
<p>Two</p>
<p>Three</p>
If we call $('p').example()
the elements <p>One</p>
, <p>Two</p>
, <p>Three</p>
will be logged to the Console, one after the other.
Question - continued
Does this type of method chaining only work with jQuery Objects, like the above, or is there a way to call this method on a variable?
e.g.
let someArray = ["one", "two", "three"];
someArray.example();
The above code will not work, as example()
is not a method of someArray
Question - final
Is there a correct way to call a jQuery method, in a chain, from a variable or object, or can you only call these methods on objects that have been "selected" with jQuery.
If you must first "select" the object with jQuery, is there a way to select a variable, rather than an element of the DOM.