Doubt with jQuery function

Asked

Viewed 41 times

1

How this function jQuery finds the tag em to execute the method prependum() ?

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>como vai</pre>
   <em>você?</em>
   <button type="button" id="btn">Anexa/desanexa par&aacute;grafos</button>
</div>

  • 1

    It does not. The first condition will be false (because false, null and undefined are considered false in Javascript), this will cause the code to jump to the else. The detach will crop the widget <em> and assign to the variable em, this way it will no longer be false and will become true. The next time the button suffers a click action, the condition will be true.

  • All right, man, I get it. Thanks for the clarification!

1 answer

0


It is not found in the first click, because at first the em is only one variable null.

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

On the second click o em will already be true and will meet the condition of if. Will make the prependTo and em will again be null again, and so on and so forth.

  • I will accept your reply :)

  • Obg! If someone posts a better answer, you can change your option. Abs!

  • It’s just that Valdeir Psr up there had already explained the operation, but, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.