Josemari Bautista
Josemari Bautista

Reputation: 87

How to get the ID of an element after it has been clicked using pure JavaScript?

So I want to return the ID of an element that is clicked so I can save that as a string value use throughout my code. For example in a rock, paper, scissors game.

 <div id ="Options">
        <div id="Rock">
            <p>Rock</p>
        </div>
         <div id="Paper">
             <p>Paper</p>
         </div>
         <div id="Scissors">
             <p>Scissors</p>
         </div>
</div>

This is the code I attempted to use so far but it's return value when clicked is still giving me undefined when I do console.log(playerChoice).


let playerChoice = Options.addEventListener("click", function(e) {
  let choice = e.target.id;
  return choice
})


Upvotes: 0

Views: 246

Answers (2)

ariel
ariel

Reputation: 16150

Target is always the child element, in that case the <p>. So you better attach the click event to the child divs, that way you get the same result even if you alter the hierarchy adding elements or images:

var options = document.querySelectorAll("#Options div");
for (el of options) {
  el.addEventListener("click", function(e) {
    let choice = this.id;
    console.log(choice);
  })
}
<div id="Options">
  <div id="Rock"><p>Rock</p></div>
  <div id="Paper"><p>Paper</p></div>
  <div id="Scissors"><p>Scissors</p></div>
</div>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370679

The e.target, if the user clicks on one of the words, will be a <p>. Check the parent element instead to get to the div:

Options.addEventListener("click", function(e) {
  const choice = e.target.parentElement.id;
  console.log(choice);
})
<div id="Options">
  <div id="Rock">
    <p>Rock</p>
  </div>
  <div id="Paper">
    <p>Paper</p>
  </div>
  <div id="Scissors">
    <p>Scissors</p>
  </div>
</div>

Could also ditch the IDs altogether and check the textContent of the clicked <p>:

Options.addEventListener("click", function(e) {
  if (e.target.matches('p')) {
    const choice = e.target.textContent;
    console.log(choice);
  }
})
<div id="Options">
  <div>
    <p>Rock</p>
  </div>
  <div>
    <p>Paper</p>
  </div>
  <div>
    <p>Scissors</p>
  </div>
</div>

Upvotes: 3

Related Questions