I’m declaring a variable containing a jQuery object in the following way $current = $('.current') at the beginning of my code. The problem is that my class current change frequently of node.
Here is an exemple
Is there a way to declare the selector at the beginning of the script and make it somehow more dynamic.
No, there is not a way to declare a jQuery variable that is always up-to-date when you add/remove items from the DOM that match its selector. That is not a feature that jQuery has.
There are many other ways to solve the problem of dynamically created elements though. For example,
document.getElementsByClassName()returns a live nodeList that is kept up to date as the document changes. And, of course, you can always just refresh your jQuery variable before using it with a fresh query of what is in the document at any given time. This is the usual recommendation for any action that it triggered by a user because refreshing the query is plenty fast for user time and is guarenteed to be accurate as of the moment the action occurs and carries no risk of memory leaks due to dangling references.In general, it is not a good idea to keep a jQuery variable around for awhile if objects in it are dynamcally created/removed because keeping the reference to them in the jQuery variable can prevent the garbage collector from cleaning up the memory from old objects (e.g. memory leaks) until the jQuery variable itself is removed.