• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

202
Views
Why does my code change the innertext back to the starting value?

This is quite a simple problem that is somehow eluding me, and my google fu is also letting me down. What I expect to happen is that the changes value and stays there. But for some reason after the function is called it returns back up to the let button = document.querySelector('#btn').addEventListener("click", ChangeText); line. And it just overwrites what I just did.

I am fully aware that I could use onclick on the button but we're meant to use eventlisteners for this.

Here is the html and js. and a jsfiddle.

https://jsfiddle.net/bgd2n381/

let button = document.querySelector('#btn').addEventListener("click", ChangeText);


function ChangeText() {
  let label = document.querySelector('#text');
  if (label.innerText == "Start Text") {
    label.innerText = "Text has been changed";
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="js/uppgift2.js" defer></script>

</head>

<body>
  <form>
    <label id="text">Start Text</label>
    <br>
    <br>
    <br>
    <button id="btn">Button</button>
  </form>

</body>

</html>

almost 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error