• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

28
Views
Text not changing when using .innerHTML and var

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 class="list">
      <a href="https://www.google.com">Google</a>
    </li>
    <li class="list">Second</li>
    <li class="list">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.

about 2 months ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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
about 2 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.