-1

document.getElementById("p").textContent += "You are now connected;"


function myFunction() {
   document.getElementById("p").textContent.replace("You are now connected;", "You are disconnected");
}
<p id ="p"></p>

<button onclick="myFunction()">out</button>

I created some text using Javascript and now I want to change the content of the text after I press a button but I am having difficulties with it.

Nicoletta
  • 57
  • 10
  • Duplicate of [JS replace not working on string](https://stackoverflow.com/questions/12231644/js-replace-not-working-on-string) – Guy Incognito Jun 10 '20 at 15:15

4 Answers4

1

It does not work since replace does not modify the original value, but instead returns the result. You can fix the code by instead assigning element.textContent to the result of replace.

function myFunction() {
   const element = document.getElementById("p")
   element.textContent = element.textContent.replace("You are now connected;", "You are disconnected");
}

In this example though there really is no point in using replace, instead of just assigning the new value.

function myFunction() {
   const element = document.getElementById("p")
   element.textContent = "You are disconnected";
}
Thomas
  • 537
  • 1
  • 4
  • 14
1

String.replace() doesn't perform the operation "in-place", it returns the string. Set the textContent to the result of the operation:

document.getElementById("p").textContent += "You are now connected;"


function myFunction() {
   document.getElementById("p").textContent = document.getElementById("p").textContent.replace("You are now connected;", "You are disconnected");
}
<p id ="p"></p>

<button onclick="myFunction()">out</button>
esqew
  • 42,425
  • 27
  • 92
  • 132
1

replace creates a new string but you are not assigning it to your element. You need to assign it.

document.getElementById("p").textContent += "You are now connected;"


function myFunction() {
  let p = document.getElementById("p");  
  p.textContent = p.textContent.replace("You are now connected;", "You are disconnected");
}
<p id ="p"></p>

<button onclick="myFunction()">out</button>
zfrisch
  • 8,474
  • 1
  • 22
  • 34
1

document.getElementById("p").innerText += "You are now connected;"


function myFunction() {
   document.getElementById("p").innerText = "You are disconnected";
}
<p id="p"></p>

<button onclick="myFunction()">out</button>