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/

Problem

Unfortunately, the reason you can't use the solution from How can I refresh a stored and snapshotted jquery selector variable is not because you've implemented anything incorrectly, but just because the solution is deprecated.

The former solution relies on the internal .selector property which was deprecated in v1.7 and removed in v3.0

Note: This API has been removed in jQuery 3.0. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set.

Solution

I think the simplest solution is just redo the selector query from scratch. No real performance difference between that and "refreshing" the query which will have to do the same thing anyway. You'll end up with a little duplicate code, but most of the other solutions require much more indirection and complexity.

So instead of relying on a shared variable in multiple places like this:

var selector = $(".div2");

function Remove() {
  selector.refresh();
  selector.remove();
}

function Add() {  
  selector.refresh();
  selector.append($main);
}

Instead, use inline like this:

function Remove() {
  $(".div2").remove();
}

function Add() {  
  $(".div2").append($main);
}