2

I'm trying to write pure javascript function to replace the text "Passed" to "Completed". The HTML inside the div#prompt should remain in tact and is variable. Here is the HTML -

<div id="prompt">
  Passed
  <a href="#">Take a survey</a>
  <button type="button" data-behavior="hide.prompt"></button>
</div>

I tried replacing text but that doesn't seem to be working

var text = document.getElementById('prompt').textContent; 
text.replace("Passed", "Completed");

Also tried this -

var text = document.getElementById('prompt').innerHTML;
text.replace("Passed", "Completed");

What am I doing wrong? Appreciate the help!

1

2 Answers 2

4

replace does not mutate the string, it returns a new one. Strings are immutable.

 var text = document.getElementById('prompt');
 text.textContent = text.textContent.replace("Passed", "Completed");

Actually your element contains a text node that you can override:

 document.getElementById('prompt').childNodes[0].textContent = "Completed";
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of replacing text, how about toggle a class on the outer div.

With that you can also customize its HTML as well.

Stack snippet

.prompt::before {
  content: 'Passed';
}
.prompt.hidden::before {
  content: 'Completed';
}
.prompt.hidden button {
  display: none;
}

/* demo styles */
.prompt button { padding: 5px 20px; }
hr { margin: 20px 0; }
<div class="prompt">
  <a href="#">Take a survey</a>
  <button type="button" data-behavior="hide.prompt"></button>
</div>

<hr>

<div class="prompt hidden">  
  <a href="#">Take a survey</a>
  <button type="button" data-behavior="hide.prompt"></button>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.