简体   繁体   中英

Javascript not able to replace text with new Text with html

I trying to replace text with new text inside a html tag like:

  text = " hello how are you? " ;
  newText = "<h1>hello how are you? </h1> " ;

This is my code:

//replacer holds the html element
 var replacer = document.getElementById("#"+id);

 var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";

//selectedinnerText holds the text to be replaced                                                                 
 alert(selectedinnerText + "      "+ newElement   );

//This below line is not working properly
replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);

Your issue is, when you are getting an element by its id in JavaScript, you do not need # infront of the id name.

var replacer = document.getElementById(id);

So, the reason why you cannot set the innerHTML of the replacer element is because there is no element stored in the variable right now.

The correct code should be

 var replacer = document.getElementById(id);// no # needed here
 var newElement = "<span style='font-size:100px;' id='one4'>"+selectedinnerText+"</span>";

alert(selectedinnerText + "      "+ newElement   );

replacer.innerHTML = replacer.innerHTML.replace(selectedinnerText,newElement);

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