0

What I'm trying to do is when you click on a button, an alert comes up with a prompt for the user to input their name in. Once the user enters their name, I want their name to appear in a h2 (class= "pName"). I can't seem to get this to work, am I coding this wrong?

Javascript

$("#newPlayer").click(function(){
        var newPlayer = prompt("Please enter your name.","");
        
        if(newPlayer != null){
            document.getElementsByClassName("pName").innerHTML = newPlayer;
        }
    });
  • When you use `document.getElementsByClassName()` you need to be aware that this returns an array of all elements with this classname. Even if there is only one element with this classname then you will still need to give an index value as such... `document.getElementsByClassName()[0]`. – James Nov 17 '20 at 01:45
  • Oh, ok I didn't realize that. I'll try that, thank you for your help! – Aly Stephan Nov 17 '20 at 02:13

2 Answers2

1

Since the document.getElementsByClassName retrieves an array of elements with the class pName, you need to pass the index. Try the below code

$("#newPlayer").click(function() {
  var newPlayer = prompt("Please enter your name.", "");

  if (newPlayer != null) {
    document.getElementsByClassName("pName")[0].innerHTML = newPlayer;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="newPlayer">New Player</button>
<h2 class="pName"></h2>
Harshana
  • 5,151
  • 1
  • 17
  • 27
0
document.getElementsByClassName("pName")[0].innerHTML = ...

with Jquery:

$('.pName').html(message);
laguf1.mobi
  • 171
  • 6