Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!