0

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.

Aaron
  • 101
  • 1
  • 10

1 Answers1

1

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>
Spectric
  • 30,714
  • 6
  • 20
  • 43