I have a selector stored in a variable. The content in the page changes dynamically, the problem I'm facing was when the content was removed then the cached selector didn't work. How can I re-evaluate or refresh the selector? https://jsfiddle.net/qehdvedd/
var selector;
function Remove(){
selector.refresh();
selector.remove();
}
function Add(){
$("#div1").append('<div class="div2">New content</div>');
}
$(document).ready(function () {
selector = $(".div2");
});
$.fn.refresh = function() {
return $(this.selector);
};
I also referenced (https://stackoverflow.com/questions/11868899/how-can-i-refresh-a-stored-and-snapshotted-jquery-selector-variable) but it does not work. I'm aware of the alternative solutions like storing the selector name as a string and calling it with jquery.
Edit: I will tell the exact scenario. I'm working on a spa website, in that if I clicked an element and go to next page in the spa. Then if I pressed Esc or back button I need to focus the last selected item also need to add a class to show which is selected. I will store the selector in a variable to know the last selected item when the element is clicked. And if the Esc key is pressed then I will focus on the variable which stored the last selected item. But due to spa the contents are removed and added dynamically. So this solution doesn't seem to work. I can't use the alternative solutions like storing the selector name as a string and calling it with jquery. Because there are too many items present on the page, so adding every item with Id is not practical. Sample: http://jsfiddle.net/2v78hmb5/