Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
What is wrong with my JavaScript Code using the innerHTML method?

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';
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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" />

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!