Doubt with jQuery function

1

How does this jQuery function find the em tag to execute the prependTo () method?

var em;

$("#btn").click(function() {
   if (em) {
      em.prependTo("pre");
      em = null;
   } else {
      em = $("em").detach();												
   }
});
em {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><em>Alô</em><pre>comovai</pre><em>você?</em><buttontype="button" id="btn">Anexa/desanexa par&aacute;grafos</button>
</div>
    
asked by anonymous 18.04.2018 / 19:46

1 answer

0

You can not find the first click, because at first em is just a null variable.

At the first click of the button, em is false , going straight to else , where em now has a value ( em = $("em").detach(); ), which is element <em> .

In the second click the em will already true and will meet the if condition. You will do prependTo and em will be null again, and so on.

    
18.04.2018 / 20:40