Receiving a console.log output that I didn't expect. But I'dont know why?

31 Views Asked by At

I'm am following a course by John Smilga to learn Javascript. I'm currently working on a chapter which contains a task with getAttribute and setAttribute.

Here is my index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Foundational knowledge</title>
    <style>
      .btn {
        font-size: 2rem;
        background: lightgray;
        text-transform: uppercase;
      }
    </style>
  </head>
  <body>
    <h1 id="title">Navigate the Dom</h1>
    <h2>getAttribute_setAttribute</h2>
    <ul>
      <li class="first" id="special">first</li>
      <a href="first.html" id="link">example link</a>
      <li>i have no attributes</li>
    </ul>
    <!-- javascript -->
    <script src="./app.js"></script>
  </body>
</html>

And here is the section of the .js file:

console.log("\n\n\n\n\n\n\n\n\n");
const last = link.nextElementSibling;
console.log(last);

// debugger;
last.setAttribute("class", "first");
last.setAttribute("id", "Pumuckl");
last.textContent = "i also have a class of first now";

console.log(last);
// Proof at the end the returning node list
links = document.querySelectorAll(".first");
console.log(links);

If I save the file to run the code, the consol.log give a outout, which I have not expected: <li class="first" id="Pumuckl">i also have a class of first now</li> <li class="first" id="Pumuckl">i also have a class of first now</li>

The first line of output I did not expect.

I tried to check why this happens. So I comment out the code like below:

console.log("\n\n\n\n\n\n\n\n\n");
const last = link.nextElementSibling;
console.log(last);

// // debugger;
// last.setAttribute("class", "first");
// last.setAttribute("id", "Pumuckl");
// last.textContent = "i also have a class of first now";

// console.log(last);
// // Proof at the end the returning node list
// links = document.querySelectorAll(".first");
// console.log(links);

After I have saved the file I get following output: li

My question is: why is that changing if uncomment the line to: <li class="first" id="Pumuckl">i also have a class of first now</li>

How the is first console.log(last); knows about attributes, which I am setting after it? I would like to know, if the behaviour comes from referencing or from the browser. I try to understand what is happening. How can I get the value before the modifiying in the console.log, to inspect the before and after output like I am expecting.

I am using VSCode and Live Extension

0

There are 0 best solutions below