1

I'm trying to add HTML from my JS file with innerHTML and its just displaying text on my HTML file instead of reading it in as image. This is my JS file and the function below is inside a class.

setCardHtml(){
    let imageHtml = this.cards.map((image) => `<img class="cards base-cards" src="/images/${image}.png">`).join('')
    for (let image of imageHtml) {
        elements.playerCards.innerHTML += image 
    }
}

This is what ends up showing on my HTML when I host the site. The images that are showing are just placeholder images in my HTML file.

enter image description here

I've triple checked the pathing to my images to make sure its leading to the image and I don't think thats the problem but here is the structure of my files.

+--_html-css-js
|   +--_css
|   |  +--bj.css
|   +--_js
|   |  +--bj.js
|   +--_html
|   |  +--bj.html
+--_images
   +images.png
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 1
    I'm a little confused about the sequence of events. You have an array that you're mapping over, which returns an array and then you then join that into a string. You're then iterating over the string (and you can do that because strings are iterable) but I don't think you mean to do that here because it would just iterate one character at a time. Did you mean to join up the array? – Andy Jun 11 '22 at 21:29
  • Also, just an aside, but this is an extremly bad way of making new HTML, as _the whole html_ will be reevaluated _every time you add a bit of innerHTML_. So you are essentially making more elements you discard every turn. This could create quite a heap in js to clear. – somethinghere Jun 11 '22 at 21:40
  • Oh, yes. [For reference](https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code). – Andy Jun 11 '22 at 21:52

2 Answers2

0

So what's happening is you created a string (which is an array of characters) when you did let imageHtml = this.cards.map((image) => ).join(''). Then then you looped through each character and appeneded it and the entire string to the innerHTML.

It would be enough to just do elements.playerCards.innerHTML += imageHtml.

setCardHtml(){
     let imageHtml = this.cards.map((image) => `<img class="cards base-cards" src="/images/${image}.png">`).join('')

     elements.playerCards.innerHTML += imageHtml   
}

Onboardmass
  • 84
  • 3
  • 11
0

By using join you are converting the array into a string. Your second loop iterates over the string and adds one character to the .innterHTML of the target element in each iteration. You don't need the second loop at all. You just need elements.playerCards.innerHTML = imageHtml.

That being said it's better to use DOM APIs for modifying the document. Using innerHTML is very inefficient. Check What is the best JavaScript code to create an img element?

Ram
  • 143,282
  • 16
  • 168
  • 197