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

175
Vistas
Accessing innerHTML in javascript for addEventListener

I tried 2 pieces of code, one of them worked and the other didn't and I am not sure as to why it happened as both the code pieces look similar to me. What I want to do is to print a different piece of text every time a user clicks on a button. First, the code that didn't work as I wanted it to and the result was always err and each time I clicked on it, neither the text changed nor the console except for the number beside err kept increasing

function func1() {
    let x = document.getElementById("test1").innerHTML;
    if (x===""){
        x = "First click";
        console.log("err");
    }
    else if (x==="First click") {
        x = "Second click";
        console.log("err2");
    }
    else {
        x = "Third click";
    }
}

document.getElementById("click").addEventListener("click", func1);

And the second piece of code that worked perfectly is :

function func1() {
    let x = document.getElementById("test1");
    if (x.innerHTML===""){
        x.innerHTML = "First click";
        console.log("err");
    }
    else if (x.innerHTML==="First click") {
        x.innerHTML = "Second click";
        console.log("err2");
    }
    else {
        x.innerHTML = "Third click";
    }
}

document.getElementById("click").addEventListener("click", func1);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Reassigning a variable does not have any side-effects (in almost all cases) - doing someVar = newValue will only cause changes if other parts of the code reference someVar later.

When you do

let x = document.getElementById("test1").innerHTML;

you invoke the .innerHTML getter of the element, which returns the HTML string and puts that string into the x variable. Putting a new string into the x variable doesn't change the element. You have to assign to the .innerHTML property of the element in order to invoke the setter, which is why

x.innerHTML = "Second click";

works.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you really want to use the x = syntax to modify the text of the element, the closest you can get is defining a property on the window to forward the value.

Object.defineProperty(window, 'x', { get: () => document.getElementById("test1").innerText, set: (val) => document.getElementById("test1").innerText = val });
x // gives text value
x = 'asdf' // sets to 'asdf'

Of course this is very over the top and unnecessary for simply avoiding adding a .innerText and I wouldn't recommend doing all that unless it is really important for your purpose.

Simpler and safer approach would be to simply define a function.

function x(v) {
  if (v) document.getElementById("test1").innerText = v;
  return document.getElementById("test1").innerText;
}
x() // gives text value
x('asdf') // sets to 'asdf'
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