JS - Dynamic List & ASSIGNMENT

Dear all,


I have a question regarding video “Javascript Next Level / Dynamic List & ASSIGNMENT”.
In Ivan’s video he adds the Variable “var list = $(’#fruitList’)”, that I don’t really understand what it’s purpose is.
Making a sketch, it goes something like this (see picture bellow):

Ivan Code

Can someone please explain how the var list = $(’#fruitList’) will look like after Step 1?
I believe it takes some shape in the background that it is not necessary to be displayed.

However, to me it makes more sense, and I can grasp my mind around the code, if we eliminate that variable, which will result in obtaining the same result. To do this we will have to append the newly created ‘lines’ to the Order list. Please see sketch bellow:
Andrei Code

Hope I have made by self understandable and thank you in advance for your help.

Kind regards,
Andrei

1 Like

Hello sir, both are valid method, the difference for the var list = $(’#fruitList’) can be used to access the elements that are on the < ol id=“fruitlist”> and apply some actions on the ordered list (if you want).

Let say for example that you want to apply some style over the list, that is when the the var list = $(’#fruitList’) comes into play.

Example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <title>fruit list</title>
  </head>
  <body>
        <h1>My favorite fruits</h1>

        <ol id="fruitlist">
          </ol>

        <script>

          var fruits = ["apple", "oranges","banana"];
          var list = $("#fruitlist").css("color", "yellow");
          $.each(fruits,function(index, value){
            $("<li/>").text(value).appendTo(list);
          });

        </script>
  </body>
</html>

That code will apply the color yellow to the elements on the list, thanks to the var list = $(’#fruitList’).

Hope this gives you a clear view of the subject, keep learning! :slight_smile:

If you have any doubt, please let us know so we can help you!

Carlos Z.

2 Likes

Dear Carlos,

Thanks for clearing the situation. Everything is crystal clear :slight_smile:

Kind regards,
Andrei

2 Likes