简体   繁体   中英

Javascript Event Listener to change paragraph text onclick of button doesn't work?

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;
}

You 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>

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