What's wrong with this code? |
What's wrong with this code? |
Hardik Modha |
Sep 20 2014, 07:36 AM
Post
#1
|
Group: Members Posts: 1 Joined: 20-September 14 Member No.: 21,572 |
Hello, I'm noob to Java script and learning it. There is some problem in the code but i can't find it. It is not giving the output as i want . Can anybody help me...!! I would appreciate if anyone helps me.!
CODE <!DOCTYPE html> <html> <head> <title>JavaScript Event</title> </head> <body onload="myFunction1();"> <p id="p1"> Hii </p> <p id="p2"> </p> <button onclick="myFunction2();">Click Me</button> <script> function myFunction1() { alert('Welcome to my Website'); document.getElementById("p1").innerHTML = "Page has been loaded"; } function myFunction2() { var x = document.getElementById("p1").innerHTML; x.style.fontSize = "large"; x.style.color = "#99FF99"; document.getElementById("p2").innerHTML = x; } </script> </body> </html> |
Frederiek |
Sep 20 2014, 10:14 AM
Post
#2
|
Programming Fanatic Group: Members Posts: 5,146 Joined: 23-August 06 From: Europe Member No.: 9 |
The var x is not an object as it points to the innerHTML, not the actual element.
For that, you need to add another variable that points to the element, using the document.getElementById(). Making the correct changes will result in two P tags and the #p1 getting the styling. I suppose you want the #p2 to get the styling. Then use the following (notice the changes I made to your function): CODE function myFunction2() { var x = document.getElementById("p1").innerHTML; var y = document.getElementById("p2"); y.style.fontSize = "large"; y.style.color = "#99FF99"; y.innerHTML = x; // shortened for document.getElementById("p2").innerHTML you had before } |
Lo-Fi Version | Time is now: 26th April 2024 - 07:50 AM |