Home > database >  What is wrong with my JavaScript Code using the innerHTML method?
What is wrong with my JavaScript Code using the innerHTML method?

Time:04-18

I'm trying to change the text in an h2 element with the simplest code but don't get what I'm doing wrong :

html

<h2 id="tries">Number of tries : 0</h2>

javascript

document.getElementById("tries").innerHTML = 'new text';

CodePudding user response:

I just guess you did that and as you can see, it will fail

<!doctype html>
<html>
<head>
    <script>
document.getElementById("tries").innerHTML = 'new text';
    </script>
</head>
<body>
    <h2 id="tries">Number of tries : 0</h2>
</body>
</html>

You can first do DOM Operations if the DOM is actually loaded, so you just listen to the window.load event and it will work

<!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>

CodePudding user response:

There is nothing wrong wiht that. You asked JS to replace the innerHTML, and JS done that.

If you want to change only the value after the ":" then here is an example where I placed a span into the the p and I change the innerHTML of this 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" />

  • Related