Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new in JavaScript and i have text "Hello World" and button under this text once i click on the button should the text change into "Hello Ben"

very basic but i will be very glad for an explanation how its working since i am new in Js

I am using consol in googlechrom so i just want JS and no HTML

What I have tried:

Hello World
<button id="clickMe">Click Me</button>


function ShowHelloMessage() {

          var GetText = document.getElementById("clickMe");
Posted
Updated 24-Sep-19 4:00am

There is 2 parts which are needed for your question

The first part is as jimmson stated in their solution; use the innerText property to set the value.

But this will not work with your code as is; as there is nothing calling your ShowHelloMessage() function. You will need to add an event property to your button to say what to do when the button is clicked
HTML
<button id="clickMe" onclick="ShowHelloMessage();">Click Me</button>
You will notice the empty parenthesis in both the function and the event calling it. You could place a variable name in the function itself there and pass that value on the button itself
HTML
<script>
function ShowHelloMessage(NewMessageValue) {
	var GetText = document.getElementById("clickMe");
	GetText.innerText = NewMessageValue;
}
</script>
<button id="clickMe" onclick="ShowHelloMessage('Mike was here!');">Click Me</button>
 
Share this answer
 
Comments
jimmson 24-Sep-19 10:07am    
Good answer.
MadMyche 24-Sep-19 10:08am    
Thank you
F-ES Sitecore 24-Sep-19 10:32am    
You might need to "return false" from that function in case the button is in a form.
[no name] 25-Sep-19 4:06am    
thank you MadMyche, thank you jimmson
You can use innerText property to change the text.
JavaScript
var GetText = document.getElementById("clickMe");
GetText.innerText = "test";


More info about innerText: JavaScript - innerText property - javatpoint[^]
 
Share this answer
 
v2

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