Search code examples
javascriptdom-manipulation

javascript [object HTMLButtonElement] displayed in UI


//UI. When play is clicked make R.P.S buttons appear
const startGame= () => {
    intro = document.querySelector('.intro');
    playBtn = document.querySelector(".playBtn");
    match = document.querySelector('.match');

    playBtn.addEventListener('click', e => {
    match.classList.add("fadeIn");
    playBtn.remove();
    });
}
//When "rock", "paper", or "scissors" is clicked generate random
//option for computer selection.
const playGame= () => {
    button = document.querySelectorAll('.buttons button');
    choices= ["rock", "paper", "scissors"];
    choiceDisplay = document.querySelector('.matchContainer');
    playerDisplay = document.querySelector('.playerDisplay');

    button.forEach(button=> {
        button.addEventListener('click', function(e) {
            
            computerSelection = choices[ Math.floor((Math.random() *choices.length))];
            
            //display computer and player choice on UI
            choiceDisplay.textContent = ` Computer: ${computerSelection } ` + " ";
            playerDisplay.innerText = " "+ ` Player: ${this}`;
        });
    });
    
}

//here is part of my HTML code:`

\<div class="buttons"\>
\<button class="rockBtn"\>Rock\</button\>//here is part of my HTML code:
\<button class="paperBtn"\>Paper\</button\>
\<button class="scissorsBtn"\>Scissors\</button\>
\</div\>

So, I have been trying to figure out why it's diplaying [object HTMLButtonElement] in my UI instead of the button pressed which can be : "rock", "paper" or "scissors" button. I tried  console.log(this) but it shows part of my HTML depending on the button choosen it choses the right one.


Solution

  • this is the element the event listener is attached to (i.e. the button variable). You want to read its textContent.

    ${this.textContent}