1
  1. put an object in a variable with jquery.
const $hoge = $('#hoge');
  1. DOM is rewritten by events etc.
$hoge.parent().html('<div id="hoge"></div>');

At this step, the variable, $hoge, is dereferenced, so I can't operate on the new element.

e.g.

$hoge.addClass('test'); // this is invalid.

Is there a way to detect $hoge in this state?

I tried...

const $hoge = $('#hoge');
console.log($hoge === $('#hoge')); // always false
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Hiroshi H
  • 31
  • 5
  • There's some confusion as, after step 2, `$hoge` is *not* "dereferenced* - it still exists fine, just no longer in the DOM. Your .addClass is not "invalid" and works fine - just it applies to the out-of-DOM element in `$hoge`. You can confirm this by adding `$("#hoge").after($hoge)` to re-insert the element(s) stored in `$hoge`. https://jsfiddle.net/Lgpdm7ub/ This doesn't stop your question, just slightly rewords it to - is there a way to detect if `$hoge` has been removed from the DOM. – freedomn-m Mar 07 '23 at 09:27
  • Updated fiddle to match solution: https://jsfiddle.net/Lgpdm7ub/1/ – freedomn-m Mar 07 '23 at 09:32
  • @freedomn-m Thank you This was exactly the answer I was looking for. https://stackoverflow.com/questions/3086068/how-do-i-check-whether-a-jquery-element-is-in-the-dom – Hiroshi H Mar 07 '23 at 12:03

0 Answers0