Looking to dynamically change the text of an h2 element nested within a div using JavaScript? No problem! Let's dive into how we can achieve this without altering the HTML file directly.
Here's the HTML structure we're working with:
<div id="button">
<h2>Click me</h2>
</div>
I've experimented with both getElementsByTagName and firstElementChild methods, but only firstElementChild seems to do the trick.
The following code snippet demonstrates that firstElementChild works as expected:
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);
}
}
However, when utilizing getElementsByTagName, the update is not reflected 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);
}
}
Although the innerText property gets updated in the HTMLCollection, the changes are not visible on the webpage itself. Why does this happen?
Additionally, why does firstElementChild only work properly when wrapped inside the window.onload event listener? Removing it results in a "cannot get properties of null" error for firstElementChild.