Inserting text content using same class multiple times

I’m currently trying to insert text content that change depending of image validation using a single class for multiple divs. Any help is appreciate!

HTML

...
<div id="trophies"><img id="trophyimage" src="//user/trophies/A.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>
<div id="trophies"><img id="trophyimage" src="//user/trophies/B.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>
<div id="trophies"><img id="trophyimage" src="//user/trophies/C.png" height="100" width="100">
<span id="text-content" class="spaner"></span></div>

Right now using the next Javascript it’s inserting the text content but it only does it once per ".spanner" class, not in the rest.

JavaScript

 var trophy = document.getElementById("trophyimage");
 if(trophy.src == "...//user/trophies/A.png"){
   var x = document.getElementsByClassName("spaner")[0]; 
   x.textContent = "Trophy A";
 }
 else if (trophy.src == "...//user/trophies/B.png"){
   var x = document.getElementsByClassName("spaner")[0];
   x.textContent = "Trophy B";
 }
 else{ var x = document.getElementsByClassName("spaner");
   x.textContent = "Null";
 }

I’m trying to figure out how to make it work using something like this:

JavaScript

var trophiestext = Array.from(document.querySelectorAll("spaner"));
trophiestext.forEach(function(troph) {
  var trophy = document.getElementById("trophyimage");
  if(trophy.src == "...//user/trophies/A.png"){
    var x = document.getElementsByClassName("spaner"); 
    x.textContent = "Trophy A";
  }
  else if (trophy.src == "...//user/trophies/B.png"){
    var x = document.getElementsByClassName("spaner");
    x.textContent = "Trophy B";
  }
  else{ var x = document.getElementsByClassName("spaner");
    x.textContent = "Null";
  }
}

Thanks in advance!

33 thoughts on “Inserting text content using same class multiple times”

Leave a Comment