Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda