Home > Net >  Text not changing when using .innerHTML and var
Text not changing when using .innerHTML and var

Time:06-24

var name = document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML = "XYZ";
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>My Website</title>
  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <h1>Hello</h1>

  <input type="checkbox">

  <button style=":active color:red;">Click Me</button>

  <ul>
    <li >
      <a href="https://www.google.com">Google</a>
    </li>
    <li >Second</li>
    <li >Third</li>
  </ul>

</body>

</html>

So, this is the code for a website, and I wanted to change the text of the last element of the document - "Third" changes to "XYZ".

When I use the following code, the text does not change.

var name=document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML="XYZ";

However, when I use this:

document.firstElementChild.lastElementChild.lastElementChild.lastElementChild.innerHTML="XYZ";

The text on the website, immediately changes. Why is this happening? All I have done is just split the code in two lines instead of writing it in one.

CodePudding user response:

In the global scope, the name variable is predefined and can only be assigned strings.

You can:

  • Use let instead of var to shadow (instead of mapping onto) global variables.
  • Use a JS module instead of a regular script to get module scope instead of global scope
  • Use an IIFE to get function scope instead of global scope
  • Use a different variable name
  • Related