The <p>
text doesn't change when I click the button.
An alert message shows that output and text variables are correct. But still the Inner Text of <p>
doesn't change.
Here's the HTML:
<input type="text" id="msg"><br>
<button onclick="Message()">Submit</button><br>
<h2>Last Message:</h2>
<p class="msg">Message</p>
This is the JS:
function Message(){
var text = document.getElementById("msg").value;
var output = document.getElementsByClassName("msg")[0].innerHTML;
output = text;
}
The <p>
text doesn't change when I click the button.
An alert message shows that output and text variables are correct. But still the Inner Text of <p>
doesn't change.
Here's the HTML:
<input type="text" id="msg"><br>
<button onclick="Message()">Submit</button><br>
<h2>Last Message:</h2>
<p class="msg">Message</p>
This is the JS:
function Message(){
var text = document.getElementById("msg").value;
var output = document.getElementsByClassName("msg")[0].innerHTML;
output = text;
}
Share
Improve this question
edited Feb 17, 2021 at 1:12
pretzelhammer
15.2k16 gold badges53 silver badges103 bronze badges
asked Nov 25, 2020 at 21:05
MohsinMohsin
868 bronze badges
5 Answers
Reset to default 5You have to set the message directly onto the innerHTML
property of the DOM node. Fixed example:
function Message() {
var text = document.getElementById("msg").value;
document.getElementsByClassName("msg")[0].innerHTML = text;
}
<input type="text" id="msg"><br>
<button onclick="Message()">Submit</button><br>
<h2>Last Message:</h2>
<p class="msg">Message</p>
Your defining a variable output
to the value of document.getElementsByClassName("msg")[0].innerHTML
then you are changing the value of output
to be the value of text
.
Primitives in javascript are passed by value, not by references.
Change var output = document.getElementsByClassName("msg")[0].innerHTML;
to document.getElementsByClassName("msg")[0].innerHTML = text
If you say something like:
var output = document.getElementsByClassName("msg")[0].innerHTML;
The value of output will just be some kind of string or similar.
Then when you change that you just change the value of the string but not the element.
What you want to do is this:
var output = document.getElementsByClassName("msg")[0];
output.innerHtml=text;
function Message(){
var text = document.getElementById("msg").value;
document.getElementsByClassName("msg").innerHTML = text;
}
You were super close.
Remove the innerHTML
from var output = document.getElementsByClassName("msg")[0].innerHTML;
and add it here:
output.innerHTML = text;
So it'll look like this.
<input type="text" id="msg"><br>
<button onclick="Message()">Submit</button><br>
<h2>Last Message:</h2>
<p class="msg">Message</p>
<script>
function Message(){
var text = document.getElementById("msg").value;
var output = document.getElementsByClassName("msg")[0];
output.innerHTML = text;
}
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742327583a4423059.html
评论列表(0条)