I ran yesterday in a problem with a jquery-selector I assigned to a variable and it\'s driving me mad.
Here is a jsfiddle with testcase:
You can also return the JQuery selector in a function, and save this function into the variable. Your code will look a bit different but it works. Every time when you execute the function, your jquery selector will search the DOM again.
In this example I used an arrow function without brackets which will return whatever is next to arrow. In this case it will return the JQuery collection.
const mySelector = () => $('.parent').find('.child').last();
console.log(mySelector().text());
$('.parent').append('- 4
')
console.log(mySelector().text());
- 1
- 2
- 3