Apply CSS class to an innerHTML element only once

Advertisements

I have 2 files:

  • data.php
  • page.php

data.php fetches a row from a sql DB and sends it to page.php

In page.php i have also a JS script that receives this row via AJAX, then this row is added dynamically to a html table via innerHTML function of this js script.

While adding the row dynamically with innerHTML i also add a css class that flashes/blinks the added row. It all works beside the fact that if i insert the 2nd,3rd,4th,… row also the previuos ones inserted blink as well how can i make them blink independently while adding to the table?

this is the css class and animation

       @keyframes flash {
            from {
                background-color: #ffab91;
            }

            to {
                background-color: none;
            }
        }

        .flash_animation {
            animation: flash 1s 1;
        }

and this is the JS function

 var html_part = document.getElementById("dynamic");
 html_part.innerHTML += "<tr id="flashing_row" class='flash_animation'><td>" + code + "</td><td>" +      name +"</td></tr>";

I want that the tr with id="flashing row" got applied the flash_animation class independently

>Solution :

You should remove the animation class from the previously-added rows before inserting the new one

e.g.

var rows = document.querySelectorAll("#dynamic .flash_animation");
rows.forEach(function(row) {
  row.classList.remove("flash_animation");
});

Demo:

document.querySelector("#test").addEventListener("click", function() {
  var code = "this is a test";
  var name = "demo";
  var rows = document.querySelectorAll("#dynamic .flash_animation");
  rows.forEach(function(row) {
    row.classList.remove("flash_animation");
  });
  var html_part = document.getElementById("dynamic");
  html_part.innerHTML += "<tr class='flash_animation'><td>" + code + "</td><td>" + name + "</td></tr>";
});
@keyframes flash {
  from {
    background-color: #ffab91;
  }

  to {
    background-color: none;
  }
}

.flash_animation {
  animation: flash 1s 1;
}
<table id="dynamic">
</table>
<button id="test">
New row
</button>

P.S. Multiple HTML elements cannot share the same ID (which would be the case with your rows once you’ve added more than one) – IDs must (self-evidently) be unique, so I removed that from the code.

Leave a ReplyCancel reply