简体   繁体   中英

javascript:Using the replace() to replace text in html

I'm trying to use the replace() function to adjust the above code to show the text: Is this all?! while keeping the text added in the innerHTML

 <p id="str">Click the button for a surprise.</p>
 <form action="#">
 <input type="submit" onclick="myFunction()" value="Enter">
 </form>

 function myFunction(){
 document.getElementById('str').innerHTML = "Is this all there is?";
 str.replace(str, "Is this all?!")
 }

You can try this

<p id="str">Click the button for a surprise.</p>
<form action="#">
<input type="submit" onclick="myFunction()" value="Enter">
</form>


function myFunction(){
var str = document.getElementById('str');
str.innerHTML = "Is this all there is? <moretext>";
str.innerHTML.replace("<moretext>", "Is this all?!");
}

First of all, you need to know what replace() function is made for. This function replace some piece of string by another string, this is not used to replace the whole string value. This is not made to replace HTML text!

see an example of replace in javascript:

var str = "Visit Microsoft!";
var res = str.replace("Microsoft","W3Schools");

The result would be: "Visit W3Schools !" , okay?

learn more at: http://www.w3schools.com/jsref/jsref_replace.asp

Now, see an example to replace HTML text:

 document.getElementById('str').innerHTML = "Is this all?!"

So, that's what your code is suposed to be:

function myFunction(){
     //Set value at innerHTML
     document.getElementById('str').innerHTML = "Is this all there is?";

     //now "Is this all there is?" is stored in str variable
     var str = document.getElementById('str').innerHTML;

     //set another text for innerHTML
     document.getElementById('str').innerHTML = "Is this all?!"


 }

also, you can't store a text in innerHTML without changing it for user. So now the text that you want to store is in str variable

basically you misunderstood replace() function

function myFunction(){
  var currentText = document.getElementById('str').innerHTML;
  var resultText = currentText + " Is this all?!";
  document.getElementById('str').innerHTML = resultText;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM