Moving Elements Around - Understanding why the code behaves this way


#1


I have a question about this exercise: https://www.codecademy.com/en/courses/web-beginner-en-v6phg/0/4?curriculum_id=50a3fad8c7a770b5fd0007a1


I can pass the exercise. That is not my issue. I am posting to get a better understanding of why things work the way they do.

Below is my answer to the exercise (the code passes ok).


$(document).ready(function () {
  $("#one").after("<p>this is my text</p>");
  var $myParagraph = $("p");
  $("#two").after($myParagraph);
});

I understand that this exercise is about moving text, but I do not really understand why the code behaves the way it does.

When I declare the variable $myParagraph, is it not hoisted?

Why does the above code work, but for example the code below would keep the paragraph under the #one ID?

What am I missing / misunderstanding here?

$(document).ready(function () {
  var $myParagraph = $("p");
  $("#one").after("<p>this is my text</p>");
  $("#two").after($myParagraph);
});

#2

I am no jQuery expert and I have only started studying it, but it seems to be it's the order of your code.

From MY understanding (I hope someone more efficient at answering will verify/correct), is that it's due to jQuery reading code in the order it's written.

It looks like (in your second block of code) $myParagraph is essentially non existent because there was never a p tag to begin with when you declared the variable. You made the variable equal to something it doesn't recognise. So whenever you call it back on the 4th line, it doesn't know what to do and leaves it as undefined.

However, in your first block of code, when you declared the variable, it KNEW to attach the p tag to its value and that's what it stored, and in turn it knew what it was targetting.

I modified the exercise a little and added a Third div and placed an image for you to notice how it changes, yet your original p tag remains unaffected.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.