简体   繁体   中英

content replace js script fails

The code below does not appear to function properly. newH2Text should replace para1. This does not happen. I used Sublime, then looked through the browser console, and even on SO's code snippet. I am almost certain I have the code verbatim.

The first paragraph, which has its own id attribute should be replaced by newH2Text which is created in my JS script. I can't find my mistake here. Please help.

PS the refresh button works properly. No issue there.

 function replaceHeading(){ var newH2=document.createElement("h2"); var newH2Text=document.createTextNode("Welcome"); newH2.appendChild(newH2Text); var myDiv=document.getElementById("id1"); var oldP=document.getElementById("para1"); myDiv.replaceChild(NewH2,oldP); } window.onload=function() { document.getElementById("btn").onclick=replaceHeading; } 
 <div id="id1"> <p id="para1">Welcome to my web page.</p> <p id="para2">Take a look around.</p> <input type="button" id="btn" value="Replace Element"> <br> <input type="button" value="refresh" onclick="location.reload()"> </div> 

NewH2 is capitalized but should be newH2 with a lowercase.

myDiv.replaceChild(newH2,oldP);

See this fiddle for an example

Update

To catch these errors earlier you can use " strict mode ". An example of this would be:

;(function(){
   "use strict";
   function replaceHeading(){
          var newH2=document.createElement("h2");
          var newH2Text=document.createTextNode("Welcome");
          newH2.appendChild(newH2Text);
          var myDiv=document.getElementById("id1");
          var oldP=document.getElementById("para1");
          myDiv.replaceChild(NewH2,oldP);
     }
}());

Which would give you the error Uncaught ReferenceError: NewH2 is not defined .

There are at least two different ways todo what you are trying:

 function replaceHeading(){ /***** CORRECTED AND WORKING var newH2=document.createElement("h2"); var newH2Text=document.createTextNode("Welcome"); newH2.appendChild(newH2Text); var oldP=document.getElementById("para1"); document.getElementById("id1").replaceChild(newH2,oldP); *//// // OR a more simpler way document.getElementById("para1").innerHTML = "<h2>Welcome</h2>"; } window.onload=function() { document.getElementById("btn").onclick=replaceHeading; } 
 <div id="id1"> <p id="para1">Welcome to my web page.</p> <p id="para2">Take a look around.</p> <input type="button" id="btn" value="Replace Element"> <br> <input type="button" value="refresh" onclick="location.reload()"> </div> 

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