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

92
Vistas
Can I change a nested h2 by using getElementsByTagName?

I want to change the text of an h2 nested under a div by manipulating DOM on Javascript (and without making changes to the HTML file).

HTML:

<div id="button">
    <h2>Click me</h2>
</div>

I tried both getElementsByTagName and firstElementChild but only firstElementChild works.

firstElementChild works here:

window.onload = function pageLoaded(){
    const button = document.getElementById("button");
    const clickMe = button.firstElementChild;

    button.onclick = changeText;
    function changeText(){
        clickMe.innerHTML = "You clicked me";
        console.log(clickMe);
    }   
}

but when getElementsByTagName is used, "You clicked me" wouldn't appear on the webpage:

window.onload = function pageLoaded(){
    const button = document.getElementById("button");
    const clickMe = button.getElementsByTagName("h2");

    button.onclick = changeText;
    function changeText(){
        clickMe.innerHTML = "You clicked me";
        console.log(clickMe);
    }   
}

The innerText of the HTMLCollection would be updated as "You clicked me" in the console. But why wouldn't it also be updated on the webpage?

Addition question: why does firstElementChild only work here when it is under the window.onload event listener? If I take window.onload away, I get the "cannot get properties of null" error for firstElementChild.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

getElementsByTagName returns an HTMLCollection. You have to get the first item in it:

window.onload = function pageLoaded(){
    const button = document.getElementById("button");
    const clickMe = button.getElementsByTagName("h2")[0];

    button.onclick = changeText;
    function changeText(){
        clickMe.innerHTML = "You clicked me";
        console.log(clickMe);
    }   
}
<div id="button">
    <h2>Click me</h2>
</div>

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