Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda