Harrison Bergman
Harrison Bergman

Reputation: 43

How to get the element id of a div element that was clicked

I'm trying to design a simple hangman game, and have a line of div elements with the ids being letters. I want to receive the id of the element that is clicked, and can't seem to figure it out.

<script>
var guesses = 5;
var word = "hangman";
var spotsLeft = 7;
$(document).ready(function(){
$(".letter").click(function(){
    $(this).hide();
    guesses--;
    if(//Psuedo-code -- if a specific letter is clicked (based on element id)
    $("#guessesLeft").html("You have " + guesses + " Guesses Left");

    if(guesses == 0){
     $("#guessesLeft").html("You are out of guesses, YOU LOST!!!");
    }
});
});    
</script>

Upvotes: 0

Views: 50

Answers (3)

Yamen Nassif
Yamen Nassif

Reputation: 2476

The other two answers are correct but i am just adding JS to them :

Only Javascript : first you need to edit your element,lets say it was like this :

<button class=".letter" onClick="getId(this.id)">Click Me!</button>
<script type="text/javascript">
function getId(clicked_id)
{
    alert(clicked_id);
}
</script>

JQuery :

var id = $(this).attr('id');

Upvotes: 1

John Bupit
John Bupit

Reputation: 10618

Use .attr() to get the value of an attribute for the element. Specifically, use:

$(".letter").click(function() {
    let letterId = $(this).attr('id');
    ...
});

Upvotes: 1

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60517

Just use the attr function to get the id attribute of the clicked element.

$(".letter").click(function(){
    $(this).hide();

    var id = $(this).attr('id');

    guesses--;
    if(//Psuedo-code -- if a specific letter is clicked (based on element id)
    $("#guessesLeft").html("You have " + guesses + " Guesses Left");

    if(guesses == 0){
     $("#guessesLeft").html("You are out of guesses, YOU LOST!!!");
    }
});

Upvotes: 5

Related Questions