How do I hide/reveal a single item that is generated by Flask?


I want to reveal the score of one line in the table onclick.

Now it only hides and shows the first score. Is there any way that I can make it so when I press the button it doesn’t reveal all the scores. Thanks!
Here is what I tried:


                {% for i in games %}
                        <td> {{i['homeTeam']}} </td>
                        <td style="display: none;" id="score"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>
                        <td> {{i['awayTeam']}} </td>
                        <td><button onclick="displayScore()">Reveal score</button></td>
                {% endfor %}


function displayScore() {
    var x = document.getElementById("score");
    if ( === "block") { = "none";
    } else { = "block";


  1. ids have to be unique. In your code you are using the same id on multiple elements (multiple tds). You can use the loop index to make your ids unique. Try something like this
<td style="display: none;" id="score_{{loop.index}}"> {{i['homeTeamScore']}} - {{i['awayTeamScore']}} </td>

This will then give you something like score_1, score_2, etc

  1. Add a data-attribute to each button so that you can identify which button was clicked. Also remove the onclick code you have on each button (we will replace it with an event listener. Something like
<td><button data-index="{{loop.index}}">Reveal score</button></td>
  1. Now add an on click event listener to the table body. Since each button is inside a table row which is also inside the table body, clicking the button will cause the event to ‘bubble’ up to the table body which will trigger the listener you have attached to the table body.

    The event listener is attached to the table body and not directly to the buttons because your buttons are dynamically generated i.e. the buttons are being added at runtime (after your javascript code already exists) which means the system is not aware of those buttons.

    document.querySelector("tbody").onclick = function(e){
        // Find out which elem which was clicked
        const clicked_elem =;

        // If this clicked elem is a button, then execute our code
        if (clicked_elem.tagName == "BUTTON"){
            // First identify which button was clicked
            const index = clicked_elem.dataset.index

            // Now get the td corresponding to that button
            var x = document.getElementById("score_" + index);

            if ( === "block") {
     = "none";
            } else {
     = "block";

Answered By – NoCommandLine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published