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

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

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 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