Quiero cambiar el texto de un h2 anidado bajo un div manipulando DOM en Javascript (y sin realizar cambios en el archivo HTML).
HTML:
<div id="button"> <h2>Click me</h2> </div>Probé getElementsByTagName y firstElementChild pero solo funciona firstElementChild.
firstElementChild trabaja aquí:
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); } }pero cuando se usa getElementsByTagName, "Hiciste clic en mí" no aparecería en la página web:
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); } }El texto interno de HTMLCollection se actualizará como "Hiciste clic en mí" en la consola. Pero, ¿por qué no se actualizaría también en la página web?
Pregunta adicional: ¿por qué firstElementChild solo funciona aquí cuando está bajo el detector de eventos window.onload? Si elimino window.onload, obtengo el error "no se pueden obtener propiedades nulas" para firstElementChild.
getElementsByTagName devuelve una HTMLCollection . Tienes que conseguir el primer elemento en él:
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>