Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I tried to run the program below but it didn't work.
please can you help me fish out the error i might have done in the code?

What I have tried:

HTML
<p>Click the button to swap the text of the DIV element:</p>

<p>Click Me</p>

<p1 id="myDIV">Para #1: Hello! Click the button on top of me to get the paragraphs interchanged.<br>

<p2 id="urDIV">Para #2: You can interchange information between this paragraph and another paragraph by clicking the button. 


function swapFunction() {
var x = document.getElementById("p1").innerText;
var y = document.getElementById("p2").innerText;
document.getElementById("p1").value = y;
document.getElementById("p2").value = x;
}

}
Posted
Updated 10-Jun-20 1:22am
v2

HTML
<p1 id="myDIV">Para #1 Hello! Click the button on top of me...</p>
<p2 id="urDIV">Para #2...</p>

function swapFunction() {
var x = document.getElementById("p1").innerText;
var y = document.getElementById("p2").innerText;
getElementById does as it's name implies; Get an Element by it's ID.
Your ID's are myDIV and urDIV, and not p1 and p2.

The text of the first paragraph reads to Hello! Click the button on top of me but there is no button.

The javascript you have have on the page is not wrapped within a script tag. so it is just going to be rendered as text on the page.

In this touched-up version, I also did a little re-naming so that variables are named with some clue as to what they actually are as opposed to x & y
HTML
<button onclick="swapFunction()">Button</button>
<p id="para1">Para #1 Hello! Click the button on top of me...<br>
<p id="para2">Para #2...

<script type="text/javascript">
function swapFunction() {
	var para1 = document.getElementById("para1");
	var para2 = document.getElementById("para2");

	var content1 = para1.innerText;
	var content2 = para2.innerText;

	para1.innerText = content2;
	para2.innerText = content1;
}
</script>
 
Share this answer
 
v2
Creating a function doesn't "attach" it to anything: You need to call the function from some interactive element in the HTML to have it respond to a user event.

See here:
HTML button tag[^]
And here:
onclick Event[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900