Estoy tratando de cambiar el texto en un elemento h2 con el código más simple, pero no entiendo lo que estoy haciendo mal:
html
<h2 id="tries">Number of tries : 0</h2>javascript
document.getElementById("tries").innerHTML = 'new text';No hay nada de malo en eso. Le pidió a JS que reemplazara el HTML interno y JS lo hizo.
Si desea cambiar solo el valor después de ":" , aquí hay un ejemplo en el que coloqué un span en la p y cambio el HTML interno de este span .
function changeText(value) { //this is the point document.getElementById("tries-value").innerHTML = value; } const input = document.querySelector("input"); input.addEventListener("change", (e) => changeText(e.target.value)); changeText(input.value) <h2 id="tries">Number of tries : <span id="tries-value">0</span></h2> <label for="input-number">Change the input:</label> <input id="input-number" value="10" type="number" />Supongo que hiciste eso y, como puedes ver, fallará.
<!doctype html> <html> <head> <script> document.getElementById("tries").innerHTML = 'new text'; </script> </head> <body> <h2 id="tries">Number of tries : 0</h2> </body> </html>Primero puede hacer operaciones DOM si el DOM está realmente cargado, así que solo escuche el evento window.load y funcionará
<!doctype html> <html> <head> <script> window.addEventListener('load', function () { document.getElementById("tries").innerHTML = 'new text'; }); </script> </head> <body> <h2 id="tries">Number of tries : 0</h2> </body> </html>